B @`@sdZddlmZddlZddlmZddlZddlZddlZddl m Z m Z m Z m Z mZmZmZmZmZddlZddlmZddlZddlmZddlmZdd lmZmZmZm Z m!Z!dd l"m#Z#m$Z$dd l%m&Z&m'Z'm(Z(dd l)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1dd l2m3Z3ddl4m5Z5ddl6m7Z7ddl8m9Z9ddl:m;Z;dZdZ?dZ@dZAde=de>de?de@deAd ZBde=de>dZCde=de>de?deAd ZDd d!d"d#d$d%d&d'd(g ZEed)d*d*ZFe9d+d,d-ZGe9eHe9d.d/d0ZId1ZJGd2d3d3eKZLd4ZMGd5d6d6eKZNd7ZOGd8d9d9eKZPd:ZQGd;d<dd?d@ZTGdAdBdBZUGdCdDdDZVGdEdFdFZWGdGdHdHeWejXZYe#eBdpeeZeZeeHeZeZeeeHeZee[eZe!ee5eYfdK dLdMZ\eHeHdNdOdPZ]e e[e dQdRdSZ^eHej_dTdUdVZ`e e e e dWdXdYZaej_e9e[dZd[d\Zbdqe9e[eZeHd^d_d`Zce$e3jddadbGdcddddeWZeej_e9eZe[dedfdgZfeeHegfe[egdQdhdiZhGdjdkdkZiGdldmdmeeZjGdndodoejZkdS)ra Module contains tools for processing Stata files into DataFrames The StataReader below was originally written by Joe Presbrey as part of PyDTA. It has been extended and improved by Skipper Seabold from the Statsmodels project who also developed the StataWriter and was finally added to pandas in a once again improved version. You can find more information on http://presbrey.mit.edu/PyDTA and https://www.statsmodels.org/devel/ )abcN)BytesIO) AnyAnyStrDictListOptionalSequenceTupleUnioncast) relativedelta) infer_dtype)max_len_string_array)BufferCompressionOptionsFilePathOrBufferLabelStorageOptions)Appenderdoc) ensure_objectis_categorical_dtypeis_datetime64_dtype) Categorical DatetimeIndexNaT Timestampconcatisna to_datetime to_timedelta)generic) DataFrame)Index)Series) get_handlezVersion of given Stata file is {version}. pandas supports importing versions 105, 108, 111 (Stata 7SE), 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12), 117 (Stata 13), 118 (Stata 14/15/16),and 119 (Stata 15/16, over 32,767 variables).zconvert_dates : bool, default True Convert date variables to DataFrame time values. convert_categoricals : bool, default True Read value labels and convert columns to Categorical/Factor variables.aindex_col : str, optional Column to set as index. convert_missing : bool, default False Flag indicating whether to convert missing values to their Stata representations. If False, missing values are replaced with nan. If True, columns containing missing values are returned with object data types and missing values are represented by StataMissingValue objects. preserve_dtypes : bool, default True Preserve Stata datatypes. If False, numeric data are upcast to pandas default types for foreign data (float64 or int64). columns : list or None Columns to retain. Columns will be returned in the given order. None returns all columns. order_categoricals : bool, default True Flag indicating whether converted categorical data are ordered.zzchunksize : int, default None Return StataReader object for iterations, returns chunks with given number of lines.z=iterator : bool, default False Return StataReader object.zNotes ----- Categorical variables read through an iterator may not have the same categories and dtype. This occurs when a variable stored in a DTA file is associated to an incomplete set of value labels that only label a strict subset of the values.a> Read Stata file into DataFrame. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.dta``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``.  z Returns ------- DataFrame or StataReader See Also -------- io.stata.StataReader : Low-level reader for Stata data files. DataFrame.to_stata: Export Stata data files. z Examples -------- Read a Stata dta file: >>> df = pd.read_stata('filename.dta') Read a Stata dta file in 10,000 line chunks: >>> itr = pd.read_stata('filename.dta', chunksize=10000) >>> for chunk in itr: ... do_something(chunk) zReads observations from Stata file, converting them into a dataframe Parameters ---------- nrows : int Number of lines to read from data file, if None read whole file. z Returns ------- DataFrame zClass for reading Stata dta files. Parameters ---------- path_or_buf : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary read() functions. z z%tcz%tCz%tdz%dz%twz%tmz%tqz%thz%tyi)returncsftjjtjjtjtdddjtjtdddjddddddtdfdd }tdfd d }tdfd d }t|}d }| rd}t|}d||<| tj }| drt }|} ||| d} n^| dr*tdt|td} |r&t| |<| S| drNt }|} ||| d} n| drt j|d} |dd} || | } n| drt j|d} |dd} || | } n| drt j|d} |ddd}|| |} nl| drt j|d } |d d!d} || | } n6| d"rD|} t|}|| |} ntd#|d$|rbt| |<| S)%a Convert from SIF to datetime. https://www.stata.com/help.cgi?datetime Parameters ---------- dates : Series The Stata Internal Format date to convert to datetime according to fmt fmt : str The format to convert to. Can be, tc, td, tw, tm, tq, th, ty Returns Returns ------- converted : Series The converted dates Examples -------- >>> dates = pd.Series([52]) >>> _stata_elapsed_date_to_datetime_vec(dates , "%tw") 0 1961-01-01 dtype: datetime64[ns] Notes ----- datetime/c - tc milliseconds since 01jan1960 00:00:00.000, assuming 86,400 s/day datetime/C - tC - NOT IMPLEMENTED milliseconds since 01jan1960 00:00:00.000, adjusted for leap seconds date - td days since 01jan1960 (01jan1960 = 0) weekly date - tw weeks since 1960w1 This assumes 52 weeks in a year, then adds 7 * remainder of the weeks. The datetime value is the start of the week in terms of days in the year, not ISO calendar weeks. monthly date - tm months since 1960m1 quarterly date - tq quarters since 1960q1 half-yearly date - th half-years since 1960h1 yearly date - ty years since 0000 ir(ii)r)csX|kr,|kr,td||ddSt|dd}tddt||D|dSdS) z Convert year and month to datetimes, using pandas vectorized versions when the date range falls within the range supported by pandas. Otherwise it falls back to a slower but more robust method using datetime. dz%Y%m)formatindexNcSsg|]\}}t||dqS)r()datetime).0ymr23/tmp/pip-unpacked-wheel-q9tj5l6a/pandas/io/stata.py szX_stata_elapsed_date_to_datetime_vec..convert_year_month_safe..)r-)maxminr getattrr%zip)yearmonthr-)MAX_YEARMIN_YEARr2r3convert_year_month_safes  zD_stata_elapsed_date_to_datetime_vec..convert_year_month_safecsd|dkr4|kr4t|ddt|ddSt|dd}dd t||D}t||d SdS) z{ Converts year (e.g. 1999) and days since the start of the year to a datetime or datetime64 Series r(z%Y)r,d)unitr-NcSs,g|]$\}}t|ddtt|dqS)r()days)r.r int)r/r0r>r2r2r3r4 szW_stata_elapsed_date_to_datetime_vec..convert_year_days_safe..)r-)r5r6r r!r7r8r%)r9r@r-value)r;r<r2r3convert_year_days_safes  zC_stata_elapsed_date_to_datetime_vec..convert_year_days_safecst|dd}|dkrL|ks,|krfdd|D}t||dSnH|dkr|ksl|krfdd|D}t||dSntd tt||d }|S) z Convert base dates and deltas to datetimes, using pandas vectorized versions if the deltas satisfy restrictions required to be expressed as dates in pandas. r-Nr>csg|]}tt|dqS))r@)r rA)r/r>)baser2r3r4szS_stata_elapsed_date_to_datetime_vec..convert_delta_safe..)r-mscs"g|]}tt|ddqS)i) microseconds)r rA)r/r>)rDr2r3r4szformat not understood)r?)r7r5r6r% ValueErrorr r!)rDZdeltasr?r-values) MAX_DAY_DELTA MAX_MS_DELTA MIN_DAY_DELTA MIN_MS_DELTA)rDr3convert_delta_safes  z?_stata_elapsed_date_to_datetime_vec..convert_delta_safeFTg?)z%tctcrE)z%tCtCz9Encountered %tC format. Leaving in Stata Internal Format.)dtype)z%tdtdz%dr>r>)z%twtw4)z%tmtm )z%tqtq)z%thth)z%tytyz Date fmt z not understood)rr6r9r5r.r@r%npisnananyastypeint64 startswith stata_epochwarningswarnobjectrZ ones_likerG)datesfmtr=rCrMZbad_locsZhas_bad_valuesZdata_colrDrE conv_datesr@r9r:Z quarter_monthZ first_monthr2)rIrJr;rKrLr<r3#_stata_elapsed_date_to_datetime_vecsj.                    rk)rhrir)cs|jddd"fdd }t|}|j|r`t|}t|rXtt||<nt||<|dkr||dd}|jd}n<|d krt d |}n"|d kr||dd}|j}n|d kr||ddd }d|j tj |j d}n|dkr"||dd}d|j tj |j d}n|dkrX||dd}d|j tj |j dd}nf|dkr||dd}d|j tj |j dk t}n.|dkr||dd}|j }ntd|dt|tjd}tddd }|||<t|d!S)#aX Convert from datetime to SIF. https://www.stata.com/help.cgi?datetime Parameters ---------- dates : Series Series or array containing datetime.datetime or datetime64[ns] to convert to the Stata Internal Format given by fmt fmt : str The format to convert to. Can be, tc, td, tw, tm, tq, th, ty l"R:iFc sVi}t|jr|r0|t}|jtjd|d<|s8|rXt|}|jj |d<|jj |d<|r|tjt |dddtj}||d<nt |dd d krB|r|jt}t jtd fd d }t|} | ||d<|r|dd} | jd|d<| j|dd|d<|rJt j td dd} t| } | ||d<ntdt|dS)Nideltar9r:z%Y)r,r@F)skipnar.)xr)cs|jd|j|jS)Ni@B)r@secondsrF)rn) US_PER_DAYr2r3fszC_datetime_to_stata_elapsed_vec..parse_dates_safe..fcSsd|j|jS)Nr+)r9r:)rnr2r2r3zJ_datetime_to_stata_elapsed_vec..parse_dates_safe..r+cSs|t|jddjS)Nr()r.r9r@)rnr2r2r3gszC_datetime_to_stata_elapsed_vec..parse_dates_safe..gzZColumns containing dates must contain either datetime64, datetime.datetime or null values.)r-)rrPrd_valuesrar^rbr_datar9r:r rr. timedeltafloatZ vectorizeapplyrArGr#) rhrlr9r@r>Z time_deltaZ date_indexZ days_in_nsrqvZ year_monthrt) NS_PER_DAYrpr-r2r3parse_dates_safeps>         z8_datetime_to_stata_elapsed_vec..parse_dates_safe)z%tcrNT)rl)z%tCrOz'Stata Internal Format tC not supported.)z%tdrQ)z%twrR)r9r@rSrT)z%tmrU)r9rVr()z%tqrWrXrY)z%thrZr[r\)z%tyr]zFormat z! is not a known Stata date format)rPzrj missing_valuer2)r{rpr-r3_datetime_to_stata_elapsed_vec`sP ,          "  rz Fixed width strings in Stata .dta files are limited to 244 (or fewer) characters. Column '{0}' does not satisfy this restriction. Use the 'version=117' parameter to write the newer (Stata 13 and later) format. c@s eZdZdS)PossiblePrecisionLossN)__name__ __module__ __qualname__r2r2r2r3rsrz Column converted from {0} to {1}, and some data are outside of the lossless conversion range. This may result in a loss of precision in the saved data. c@s eZdZdS)ValueLabelTypeMismatchN)rrrr2r2r2r3rsrz Stata value labels (pandas categories) must be strings. Column {0} contains non-string labels which will be converted to strings. Please check that the Stata data file created has not lost information due to duplicate labels. c@s eZdZdS)InvalidColumnNameN)rrrr2r2r2r3rsra; Not all pandas column names were valid Stata variable names. The following replacements have been made: {0} If this is not what you expect, please make sure you have Stata-compliant column names in your DataFrame (strings only, max 32 characters, only alphanumerics and underscores, no Stata reserved words) c@s eZdZdS)CategoricalConversionWarningN)rrrr2r2r2r3rsra One or more series with value labels are not fully labeled. Reading this dataset with an iterator results in categorical variable with different categories. This occurs since it is not possible to know all possible values until the entire dataset has been read. To avoid this warning, you can either read dataset without an iterator, or manually convert categorical data by ``convert_categoricals`` to False and then accessing the variable labels through the value_labels method of the reader. )datar)c Csd}tjtjtjftjtjtjftjtjtjftjtjtjff}t ddd}t ddd}xF|D]<}||j }x|D]z}||dkr~|| t |dj kr|d}n|d}|dtjkr|| d krtd d }|||||<q~W|tjkrB|| d ks,||d kr||tj||<qh|tjkr|| dksr||dkr||tj||<qh|tjkr|| dkr||dkr||tj||<nD||tj||<|| d ks||dkrtdd }qh|tjtjfkrh|| }t|rLtd|d|tjkrx||krx||tj||<qh|tjkrh||krhtd|d|d|dqhW|rt|t|S)a- Checks the dtypes of the columns of a pandas DataFrame for compatibility with the data types and ranges supported by Stata, and converts if necessary. Parameters ---------- data : DataFrame The DataFrame to check and convert Notes ----- Numeric columns in Stata must be one of int8, int16, int32, float32 or float64, with some additional value restrictions. int8 and int16 columns are checked for violations of the value restrictions and upcast if needed. int64 data is not usable in Stata, and so it is downcast to int32 whenever the value are in the int32 range, and sidecast to float64 when larger than this range. If the int64 values are outside of the range of those perfectly representable as float64 values, a warning is raised. bool columns are cast to int8. uint columns are converted to int of the same size if there is no loss in precision, otherwise are upcast to a larger type. uint64 is currently not supported since it is concerted to object in a DataFrame. z.)keyrr(i}zaStata value labels for a single variable must have a combined length less than 32,000 characters.)rPrX)rGnamelabname _encodingcat categorieslistr8r^arangelen value_labelssorttext_lentxtn isinstancestrrerfvalue_label_mismatch_docr,rencodeappendarrayroffval)selfrrroffsetsrHvlcategoryr2r2r3__init__gs>       zStataValueLabel.__init__) byteorderr)c Cs:|j}t}d}|t|d|jt|jdd|}|dkrLdnd}t ||d}||x"t dD]}|td |qrW|t|d|j |t|d|j x$|j D]}|t|d|qWx$|jD]} |t|d| qWx|jD]} || |qW|d |S) a! Generate the binary representation of the value labels. Parameters ---------- byteorder : str Byte order of the output Returns ------- value_label : bytes Bytes containing the formatted value label iN )zutf-8utf8r(rYcr)rrwriter~packrrrr _pad_bytesrangerrrrrseekread) rrrbio null_byterZlab_lenroffsetrBtextr2r2r3generate_value_labels(     z$StataValueLabel.generate_value_labelN)r) rrr__doc__r%rrbytesrr2r2r2r3r[s ,rc@s0eZdZUdZiZeeefed<dZ x@e D]8Z dee <x*e ddD]Z de de ee e <qDWq,WdZed d d Zxpe dD]dZ ed ed Zdee<e d kreee de 7<ed ed ed eZed eZqWd Zeddd Zxte dD]hZ eded Zdee<e d krJeee de 7<ededed eZedeZq Wddded ed eded dZeeefdddZeedddZeeeefdddZedddZeddd Zee d!d"d#Z!e"e#j$eeefd$d%d&Z%d'S)(StataMissingValuea An observation's missing value. Parameters ---------- value : {int, float} The Stata missing value code Notes ----- More information: Integer missing values make the code '.', '.a', ..., '.z' to the ranges 101 ... 127 (for int8), 32741 ... 32767 (for int16) and 2147483621 ... 2147483647 (for int32). Missing values for floating point data types are more complex but the pattern is simple to discern from the following table. np.float32 missing values (float in Stata) 0000007f . 0008007f .a 0010007f .b ... 00c0007f .x 00c8007f .y 00d0007f .z np.float64 missing values (double in Stata) 000000000000e07f . 000000000001e07f .a 000000000002e07f .b ... 000000000018e07f .x 000000000019e07f .y 00000000001ae07f .z MISSING_VALUES)eii.r(`szs          z(StataMissingValue.get_base_missing_valueN)&rrrrrrrxr__annotations__basesbrrchrZ float32_baser~r incrementrrZ int_valueZ float64_baserr rArpropertyrrBrrrboolr classmethodr^rPrr2r2r2r3rsP #     rc@seZdZddZdS) StataParserc CsttttddddtddDdttjfdttjfdttjfdttj fd ttj fg|_ ttj ttj ttj ttjttjttjd |_ ttdtd |_d d ddddd |_d}d}d}d}dddt td|dt td|dft td|dt td|dfd|_ddddd d|_ddd t tdd!dt tdd"dd|_d#d$d%d&d'd(d)|_d*|_dS)+Nr(cSsg|]}tdt|qS)a)r^rPr)r/rr2r2r3r4bsz(StataParser.__init__..)iiiiiiZbhlfdQr>rqlhrss~ss)ir+)ii)iiz)bilfr+riissi1i2i4Zf4Zf8u8)rrrrqr>r)d?d@Z.e(e(dAdBdCZ/e(e ee(dDdEdFZ0e(e1ee1ee2e feffe eee(dGdHdIZ3e4eddJdKZ5e1eefddLdMZ6e1ee1ee2e feffddNdOZ7Z8S)S StataReaderTNF) path_or_buf convert_datesconvert_categoricals index_colconvert_missingpreserve_dtypescolumnsorder_categoricals chunksizestorage_optionsc stg|_||_||_||_||_||_||_||_ d|_ | |_ d|_ |j dkr^d|_ nt | trp| dkrxtdd|_d|_d|_d|_d|_d|_d|_d|_ttj|_t|d| dd} | j} WdQRXt| |_ |!|"dS)NrFr(rz.chunksize must be a positive integer when set.rb)r+is_text)#superr col_sizes_convert_dates_convert_categoricals _index_col_convert_missing_preserve_dtypes_columns_order_categoricalsr _chunksize_using_iteratorrrArGZ_has_string_dataZ_missing_values_can_read_value_labels_column_selector_set_value_labels_read _data_read_dtype _lines_read_set_endiannesssysr_native_byteorderr&handlerrr" _read_header _setup_dtype) rr"r#r$r%r&r'r(r)r*r+handlescontents) __class__r2r3rsF    zStataReader.__init__)r)cCs|S)z enter context manager r2)rr2r2r3 __enter__-szStataReader.__enter__cCs |dS)z exit context manager N)close)rexc_type exc_value tracebackr2r2r3__exit__1szStataReader.__exit__cCs|jdS)z close the handle if its open N)r"rI)rr2r2r3rI5szStataReader.closecCs|jdkrd|_nd|_dS)zC Set string encoding which depends on file version vzlatin-1zutf-8N)format_versionr)rr2r2r3 _set_encoding9s zStataReader._set_encodingcshjd}td|ddkr*n |tddjDdk_fddjD_ dS)Nr(rr.csg|]}|qSr2) _calcsize)r/typ)rr2r3r4Ls) r"rr~r_read_new_header_read_old_headerrtyplistZhas_string_datar/)r first_charr2)rr3rCBs    zStataReader._read_headercCs|jdt|jd|_|jdkr:ttj|jd||jd|jddkrbdpdd|_|jd |jd krd nd }|jd krd nd}t |j||j|d|_ |jd| |_ |jd||_|jd||_|jd|jd|jdt |jd|jddd|_t |jd|jddd|_t |jd|jddd|_t |jd|jddd|_t |jd|jddd|_||_|jdt |jd|jddd|_t |jd|jddd|_t |jd|jddd|_||j\|_|_|j|j| |_!|j|jt |jd|j d|jd |j ddd|_"|j|j|#|_$|j|j|%|_&|j|j|'|_(dS)NrrY)urNw)versionsMSF><rNHIr[rXrrT rr r\rr())r"rrArOrG_version_errorr,rPrr~rnvar _get_nobsnobs_get_data_label _data_label_get_time_stamp time_stampZ_seek_vartypesZ_seek_varnamesZ_seek_sortlistZ _seek_formats_seek_value_label_names_get_seek_variable_labelsZ_seek_variable_labels data_location seek_strlsseek_value_labels _get_dtypesrVdtyplistr _get_varlistvarlistsrtlist _get_fmtlistfmtlist _get_lbllistlbllist_get_variable_labels_variable_labels)r nvar_typeZ nvar_sizer2r2r3rTNs\             $$$$$  $$$    zStataReader._read_new_header) seek_vartypesr)csj|fddtjD}ttttfdfdd fdd|D}ttttjfdfdd fd d|D}||fS) Ncs*g|]"}tjdjddqS)r_r[r)r~rrr"r)r/_)rr2r3r4sz+StataReader._get_dtypes..)rSr)c sP|dkr |Sy j|Stk rJ}ztd|d|Wdd}~XYnXdS)Nizcannot convert stata types [])rKeyErrorrG)rSerr)rr2r3rqs  z"StataReader._get_dtypes..fcsg|] }|qSr2r2)r/rn)rqr2r3r4sc sT|dkrt|Sy j|Stk rN}ztd|d|Wdd}~XYnXdS)Nizcannot convert stata dtype [r)rrrrG)rSr)rr2r3rts  z"StataReader._get_dtypes..gcsg|] }|qSr2r2)r/rn)rtr2r3r4s) r"rrrjrAr rr^rP)rrZ raw_typlistrVrwr2)rqrtrr3rvs  zStataReader._get_dtypescs,jdkrdndfddtjDS)NrN!csg|]}jqSr2)_decoder"r)r/r)rrr2r3r4sz,StataReader._get_varlist..)rOrrj)rr2)rrr3rxszStataReader._get_varlistcsNjdkrdn$jdkr dnjdkr0dndfdd tjDS) NrN9q1hrVrTcsg|]}jqSr2)rr"r)r/r)rrr2r3r4sz,StataReader._get_fmtlist..)rOrrj)rr2)rrr3r{s   zStataReader._get_fmtlistcs>jdkrdnjdkr dndfddtjDS)NrNrrrrfcsg|]}jqSr2)rr"r)r/r)rrr2r3r4sz,StataReader._get_lbllist..)rOrrj)rr2)rrr3r}s   zStataReader._get_lbllistcsdjdkr$fddtjD}n<jdkrHfddtjD}nfddtjD}|S)NrNcsg|]}jdqS)iA)rr"r)r/r)rr2r3r4sz4StataReader._get_variable_labels..rcsg|]}jdqS)Q)rr"r)r/r)rr2r3r4scsg|]}jdqS)r)rr"r)r/r)rr2r3r4s)rOrrj)rZvlblistr2)rr3rs   z StataReader._get_variable_labelscCsJ|jdkr(t|jd|jddSt|jd|jddSdS)NrNrrrr`rX)rOr~rrr"r)rr2r2r3rks zStataReader._get_nobscCs|jdkr:t|jd|jdd}||j|S|jdkrntd|jdd}||j|S|jdkr||jd S||jd SdS) NrNr_r[rrXrr(rrr)rOr~rrr"rr)rstrlenr2r2r3rms   zStataReader._get_data_labelcCs|jdkr4td|jdd}|j|dS|jdkrhtd|jdd}||j|S|jdkr||jdStdS) NrNrr(rzutf-8rXr)rOr~rr"rdecoderrG)rrr2r2r3ros   zStataReader._get_time_stampcCsd|jdkr.|jd|jd|jddS|jdkrZt|jd|jdddStdS) NrXrrrNrr) rOr"rrqrjr~rrrG)rr2r2r3rrs    "z%StataReader._get_seek_variable_labels)rWr)c sFtd|d_jdkr.ttjjdtdjdddkrVdpXd_ tdjdd_ jdtj djd d_ _ __jd krfd d tj D}n^jj }tj|tjd }g}x:|D]2}|jkr.|j|n||dq Wyfdd |D_WnJtk r}z*ddd|D}td|d|Wdd}~XYnXyfdd |D_WnJtk r}z*ddd|D}td|d|Wdd}~XYnXjd kr2fdd tj D_nfdd tj D_tj dj djd j ddd___ !_"jdkr6xtj djdd} jd krtj djdd} ntj djd d} | dkr$Pj| qWj#_$dS)Nrr)rrrorrs)rZr(r\r]r_r[rcsg|]}tjdqS)r()ordr"r)r/r)rr2r3r4$sz0StataReader._read_old_header..)rPcsg|]}j|qSr2)r)r/rS)rr2r3r40s,css|]}t|VqdS)N)r)r/rnr2r2r3 2sz/StataReader._read_old_header..zcannot convert stata types [rcsg|]}j|qSr2)r)r/rS)rr2r3r45scss|]}t|VqdS)N)r)r/rnr2r2r3r7szcannot convert stata dtypes [csg|]}jdqS)r)rr"r)r/r)rr2r3r4<scsg|]}jdqS)rf)rr"r)r/r)rr2r3r4@srrhrrrX)%r~rrOrGrir,rPr"rrZfiletyperjrkrlrmrnrorprr^ frombufferrrrrVjoinrwryrzr{r|r}r~rrtellrs) rrWrVbufZtyplistbtprZ invalid_typesZinvalid_dtypesZ data_typeZdata_lenr2)rr3rUsp &        $$        zStataReader._read_old_headercCs|jdk r|jSg}xlt|jD]^\}}||jkr`tt|}|dt||j|j|fq |dt|dt|fq Wt ||_|jS)z"Map between numpy and state dtypesNsS) r= enumeraterVrr rrrr^rP)rdtypesrrSr2r2r3rDfs   $" zStataReader._setup_dtype)rir)cCst|tr|St|j|S)N)rrAr~calcsizer)rrir2r2r3rRvs zStataReader._calcsize)rr)cCsX|dd}y ||jStk rR|j}d|d}t|t|dSXdS)Nrrz@ One or more strings in the dta file could not be decoded using z, and so the fallback encoding of latin-1 is being used. This can happen when a file has been incorrectly encoded by Stata or some other software. You should verify the string values returned are correct.zlatin-1) partitionrrUnicodeDecodeErrorrerfUnicodeWarning)rrrmsgr2r2r3r{s   zStataReader._decodec Cs|jr dS|jdkr$d|_i|_dS|jdkr>|j|jn.|jdk sLt|j|jj }|j|j |d|_i|_x|jdkr|j ddkrP|j d}|sP|jdkr| |j d}n| |j d}|j d t |jd |j dd }t |jd |j dd }tj|j d||jd |d }tj|j d||jd |d }t|}||}||}|j |} i|j|<xTt|D]H} | |dkr|| dn|} | | || | |j||| <qW|jdkr||j dq|Wd|_dS)NrTrXs|j?|}|sg}d }x|D]}||j2} | t2tj@t2tjAfkrnt2tjB} d}n8| t2tjCt2tjDt2tjEfkrt2tjF} d}|4|||G| fq0W|rt6t7|}|dk r|%|H|}|S)NrT)r(rX)rPr)Z convert_dtypecSsg|] }|dk qS)Nr2)r/Zdtypr2r2r3r4[sz$StataReader.read..F)rnr)cstfddtDS)Nc3s|]}|VqdS)N)rc)r/ri)rnr2r3rtsz;StataReader.read..any_startswith..)r` _date_formats)rnr2)rnr3any_startswithssz(StataReader.read..any_startswithcsg|] }|qSr2r2)r/rn)rr2r3r4vsr)Irlr9r<rIr#ryr0r1r3r4r5r6r2rOr;rr=rr>rr6r StopIterationr"rrsr^rrrrAZbyteswap newbyteorderrZ from_recordsr(rZ set_index_do_select_columnsrGr8rVrrAryr _insert_strlswhererwr-rPrgrr% from_dictr_do_convert_missingrrr|rk_do_convert_categoricalsrr~Zfloat16rr}rrrrbrapop)rrr#r$r%r&r'r(r)rPZ max_read_lenread_lenr read_linesrixrrSZcols_Zrequires_type_conversiondata_formattedrcolsZ retyped_dataconvertr2)rr3rs                         zStataReader.read)rr&r)cCsTi}xt|D]\}}|j|}||jkr0qtt|}|j|\}}||} t| |k| |k} | snq|rtt | d} tj | | dd\} } t | t d}xft| D]&\}}t |}| | |k}||j|<qWn2| j}|tjtjfkrtj}t | |d}tj|| <|||<qW|rP|j}t|}t||jd|gd}||}|S)NrT)Zreturn_inverse)rPr()rrVrr rr^ logical_orr`ZnonzeroZasarrayuniquer%rgrilocrPrr}nanr(r#rZdrop)rrr& replacementsrZcolnameriZnminZnmaxZseriesmissingZ missing_locZumissingZ umissing_loc replacementjZumrlocrPr(Zreplacement_dfZreplacedr2r2r3rs>        zStataReader._do_convert_missing)rr)csptdrtjdkr|SxNtjD]@\}}|dkr:q(fdd|jdd|fD|jdd|f<q(W|S)Nrrrcsg|]}jt|qSr2)rr)r/k)rr2r3r4sz-StataReader._insert_strls..)hasattrrrrrVr)rrrrSr2)rr3rs2zStataReader._insert_strls)rr(r)c Cs|jst|}t|t|kr&td||j}|rRdt|}td|g}g}g}g} xX|D]P} |j| } | |j | | |j | | |j | | |j | qhW||_ ||_ ||_ | |_ d|_||S)Nz"columns contains duplicate entriesz, z|j D]&}|| kr|| |q||qWn t| }y ||_ Wnltk rX}zLt|}t|j|dk}dd|}d|d|d}t||Wdd}~XYnXt||jd}|||fq||||fqWtt|}|S) zC Converts categorical columns to Categorical type. N)rZorderedr(zQ-------------------------------------------------------------------------------- r'z Value labels for column a are not unique. These cannot be converted to pandas categoricals. Either read the file with `convert_categoricals` set to False or use the low level interface in `StataReader` to separately read the values and the value_labels. The repeated labels are: )r-)rkeysr8r^risinr8allrerfcategorical_conversion_warningrrrrrHrGr%Z value_countsr-rr#rr)rrrr~r)rZcat_converted_datarlabelrrcolumnZ key_matchesZinitial_categoriesZcat_datarrrZvcZ repeated_catsZrepeatsrZ cat_seriesr2r2r3rsH         z$StataReader._do_convert_categoricalscCs|jS)z2 Return data label of Stata file. )rn)rr2r2r3 data_label:szStataReader.data_labelcCstt|j|jS)z Return variable labels as a dict, associating each variable name with corresponding label. Returns ------- dict )rr8ryr)rr2r2r3variable_labelsAs zStataReader.variable_labelscCs|js||jS)z Return a dict, associating each variable name a dict, associating each value its corresponding label. Returns ------- dict )r;rr)rr2r2r3rLs zStataReader.value_labels) TTNFTNTNN)N)NNNNNNNN)9rrr_stata_reader_docrrrrrr rArrrHrMrIrPrCrTr rr r^rPrvrxr{r}rrkrmrorrrrUrDrRrrrr#rrr_read_method_docrrrrrrxrrrrr __classcell__r2r2)rGr3r!sr6.  N0     V66' #D r!TF) filepath_or_bufferr#r$r%r&r'r(r)r*iteratorr+r)c CsDt|||||||||| d } | s$|r(| Sz | } Wd| X| S)N) r#r$r%r&r'r(r)r*r+)r!rrI) rr#r$r%r&r'r(r)r*rr+readerrr2r2r3 read_stata[s"  r) endiannessr)cCs4|dkrdS|dkr dStd|ddS)N)r]littler])r\bigr\z Endianness z not understood)lowerrG)rr2r2r3r?s   r?)rrr)cCs2t|tr|d|t|S|d|t|S)zQ Take a char string and pads it with null bytes until it's length chars. r)rrr)rrr2r2r3rs r)rir)cCs(|dkrttjStd|ddS)zK Convert from one of the stata date formats to a type in TYPE_MAP. )rNz%tcrQz%tdrRz%twrUz%tmrWz%tqrZz%thr]z%tyzFormat z not implementedN)r^rPr}NotImplementedError)rir2r2r3_convert_datetime_to_stata_types r)r#ryr)cCszi}xp|D]h}||ds,d||||<||krN|||||iq t|ts`td||||iq W|S)N%z0convert_dates key must be a column or an integer)rcupdater-rrArG)r#ryZnew_dictrr2r2r3_maybe_convert_to_int_keyss  r)rPrr)cCs~|jtjkr$tt|j}t|dS|tjkr2dS|tjkr@dS|tj krNdS|tj kr\dS|tj krjdSt d|dd S) a Convert dtype types to stata types. Returns the byte of the given ordinal. See TYPE_MAP and comments for an explanation. This is also explained in the dta spec. 1 - 244 are strings of this length Pandas Stata 251 - for int8 byte 252 - for int16 int 253 - for int32 long 254 - for float32 float 255 - for double double If there are dates to convert, then dtype will already have the correct type inserted. r(rrrrrz Data type z not supported.N) rr^object_rrrur5r}rrrrr)rPrrr2r2r3_dtype_to_stata_types       rr)r dta_version force_strlr)cCs|dkrd}n d}|rdS|jtjkrntt|j}||krX|dkrHdStt|j dt t |ddS|tj kr|dS|tj krd S|tjkrd S|tjks|tjkrd Std |d dS)a Map numpy dtype to stata's default format for this type. Not terribly important since users can change this in Stata. Semantics are object -> "%DDs" where DD is the length of the string. If not a string, raise ValueError float64 -> "%10.0g" float32 -> "%9.0g" int64 -> "%9.0g" int32 -> "%12.0g" int16 -> "%8.0g" int8 -> "%8.0g" strl -> "%9s" rXiz%9srr(rz%10.0gz%9.0gz%12.0gz%8.0gz Data type z not supported.N)rr^rrrrurGexcessive_string_length_errorr,rrr5r}rrrrr)rPrrr max_str_lenrr2r2r3_dtype_to_default_stata_fmts*    rr+)r+c s<eZdZdZdZdZdOeeee e e fe ee ee j ee ee e e feed fdd Ze dd d d Zedd ddZeedddZeedddZddddZe e dddZeedddZeddddZeddd d!Zddd"d#Zddd$d%Zddd&d'Zddd(d)Zddd*d+Z ddd,d-Z!ddd.d/Z"ddd0d1Z#ddd2d3Z$dPee ee j dd4d5d6Z%ddd7d8Z&ddd9d:Z'ddd;d<Z(ddd=d>Z)ddd?d@Z*dddAdBZ+eeddCdDZ,e-j.ddEdFZ/e-j.ddGdHdIZ0e1e e dJdKdLZ2e edJdMdNZ3Z4S)Q StataWritera A class for writing Stata binary dta files Parameters ---------- fname : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary write() functions. If using a buffer then the buffer will not be automatically closed after the file is written. data : DataFrame Input to save convert_dates : dict Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are 'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to 'tc'. Raises NotImplementedError if a datetime column has timezone information write_index : bool Write the index to Stata dataset. byteorder : str Can be ">", "<", "little", or "big". default is `sys.byteorder` time_stamp : datetime A datetime to use as file creation date. Default is the current time data_label : str A label for the data set. Must be 80 characters or smaller. variable_labels : dict Dictionary containing columns as keys and variable labels as values. Each label must be 80 characters or smaller. compression : str or dict, default 'infer' For on-the-fly compression of the output dta. If string, specifies compression mode. If dict, value at key 'method' specifies compression mode. Compression mode must be one of {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}. If compression mode is 'infer' and `fname` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). If dict and compression mode is one of {{'zip', 'gzip', 'bz2'}}, or inferred as one of the above, other entries passed as additional compression options. .. versionadded:: 1.1.0 {storage_options} .. versionadded:: 1.2.0 Returns ------- writer : StataWriter instance The StataWriter instance has a write_file method, which will write the file to the given `fname`. Raises ------ NotImplementedError * If datetimes contain timezone information ValueError * Columns listed in convert_dates are neither datetime64[ns] or datetime.datetime * Column dtype is not representable in Stata * Column listed in convert_dates is not in DataFrame * Categorical label contains more than 32,000 characters Examples -------- >>> data = pd.DataFrame([[1.0, 1]], columns=['a', 'b']) >>> writer = StataWriter('./data_file.dta', data) >>> writer.write_file() Directly write a zip file >>> compression = {{"method": "zip", "archive_name": "data_file.dta"}} >>> writer = StataWriter('./data_file.zip', data, compression=compression) >>> writer.write_file() Save a DataFrame with dates >>> from datetime import datetime >>> data = pd.DataFrame([[datetime(2000,1,1)]], columns=['date']) >>> writer = StataWriter('./date_data_file.dta', data, {{'date' : 'tw'}}) >>> writer.write_file() rzlatin-1NTinfer) fnamerr# write_indexrrprr compressionr+c st|dkrin||_||_||_||_||_| |_d|_| || |_ |dkr^t j }t ||_||_tjtjtjd|_i|_dS)N)rrr)r.rr0 _write_index _time_stamprnr _compression _output_file_prepare_pandasr+r@rr? _byteorder_fnamer^rrrZtype_converters_converted_names) rrrr#rrrprrrr+)rGr2r3ras   zStataWriter.__init__)to_writer)cCs|jj||jdS)zS Helper to call encode before writing to file for Python 3 compat. N)rErBrrr)rrr2r2r3_writeszStataWriter._write)rBr)cCs|jj|dS)z? Helper to assert file is open before writing. N)rErBr)rrBr2r2r3 _write_bytesszStataWriter._write_bytes)rr)c s*fddD}||_g|_t|s*Stj}g}xt|D]\}}|rt||jd}|j||j j j }|t j krtd|j j j} | ||kr|t jkrt j}n|t jkrt j}nt j}t j| |d} ||| | dk<||| fq@|||fq@Wtt|S)z Check for categorical columns, retain categorical information for Stata file and convert categorical data to int csg|]}t|jqSr2)rrP)r/r)rr2r3r4sz5StataWriter._prepare_categoricals..)rzCIt is not possible to export int64-based categorical data to Stata.)rPrh) _is_col_cat _value_labelsr`rrr8rrrrcodesrPr^rbrGrucopyr5rrrr}rr#rr) rrZis_catrrrZ col_is_catZsvlrPrHr2)rr3_prepare_categoricalss6    z!StataWriter._prepare_categoricalscCs^xX|D]P}||j}|tjtjfkr|tjkr:|jd}n |jd}|||||<qW|S)z Checks floating point data columns for nans, and replaces these with the generic Stata for missing value (.) rqr>)rPr^rr}rfillna)rrrrPrr2r2r3 _replace_nanss     zStataWriter._replace_nans)r)cCsdS)zNo-op, forward compatibilityNr2)rr2r2r3_update_strl_namesszStataWriter._update_strl_names)rr)cCsVxP|D]H}|dks|dkr|dks*|dkr|dks:|dkr|dkr||d}qW|S)a Validate variable names for Stata export. Parameters ---------- name : str Variable name Returns ------- str The validated name with invalid characters replaced with underscores. Notes ----- Stata 114 and 117 support ascii characters in a-z, A-Z, 0-9 and _. AZrzr9r)replace)rrrr2r2r3_validate_variable_names z#StataWriter._validate_variable_namecCsi}t|j}|dd}d}xt|D]\}}|}t|tsFt|}||}||jkrbd|}d|dkrzdkrnnd|}|dtt|d}||ksx@| |dkrdt||}|dtt|d}|d7}qW|||<|||<q(Wt ||_|j rHx:t ||D],\} } | | kr|j | |j | <|j | =qW|rg} x.| D]"\}}|d|} | | q\Wtd | } t| t||_||S) a Checks column names to ensure that they are valid Stata column names. This includes checks for: * Non-string names * Stata keywords * Variables that start with numbers * Variables with names that are too long When an illegal variable name is detected, it is converted, and if dates are exported, the variable name is propagated to the date conversion dictionary Nrrrrrr(z -> z )rr(rrrrr r6rrr$r0r8itemsrinvalid_name_docr,rrerfrrr)rrZconverted_namesr(Zoriginal_columnsZduplicate_var_idrr orig_nameroZconversion_warningrrr2r2r3_check_column_namessJ           zStataWriter._check_column_names)rr)cCsVg|_g|_xD|D]8\}}|jt||j||jt||j|qWdS)N)r|rVrrrrr)rrrrPr2r2r3_set_formats_and_types1 s z"StataWriter._set_formats_and_typescCs,|}|jr$|}t|tr$|}||}t|}||}||}|j \|_ |_ ||_ |j |_|j}x.|D]&}||jkrqvt||rvd|j|<qvWt|j|j|_x*|jD] }t|j|}t|||<qW||||jdk r(x,|jD]"}t|tr|j||j|<qWdS)NrN)rrZ reset_indexrr#rrrrshaperlrjrr(tolistryrr0rrrr^rP_encode_stringsrrAr|)rrtemprrrnew_typer2r2r3r8 s:             zStataWriter._prepare_pandasc Cs|j}t|dg}xt|jD]\}}||ks||kr8q|j|}|j}|jtjkrt|dd}|dkst |dks|j }t d|d|j|j |j}tt|j|jkr||j|<qWdS) z Encode strings in dta-specific encoding Do not encode columns marked for date conversion or for strL conversion. The strL converter independently handles conversion and also accepts empty string arrays. _convert_strlT)rmrrzColumn `a` cannot be exported. Only string-like object arrays containing all strings or a mix of strings and None can be exported. Object arrays containing only null values are prohibited. Other object types cannot be exported and must first be converted to one of the supported types.N)r0r7rrrPrr^rrrrrGrrrrrru_max_string_length) rr# convert_strlrrrrPZinferred_dtypeencodedr2r2r3r!o s"     zStataWriter._encode_stringsc Cst|jd|jd|jdn|_|jjddk rV|jjt|_|j_|jj |jjy|j |j |j d||||||||||}|||||||Wntk r}zt|jt|jt t!j"frnt!j#$|jrnyt!%|jWn,t&k rlt'(d|jdt)YnX|Wdd}~XYnXWdQRXdS)NwbF)rr-r+method)rrpz!This save was not successful but z. could not be deleted. This file is not valid.)*r&rrr+rErrBrrZcreated_handlesr _write_headerrnr _write_map_write_variable_types_write_varnames_write_sortlist_write_formats_write_value_label_names_write_variable_labels_write_expansion_fields_write_characteristics _prepare_data _write_data _write_strls_write_value_labels_write_file_close_tag_close ExceptionrIrrosPathLikepathisfileunlinkOSErrorrerfResourceWarning)rrecordsexcr2r2r3 write_file sP       zStataWriter.write_filecCsF|jdk rBt|jjtst|jj|j}|j_|jj|dS)z Close the file if it was created by the writer. If a buffer or file-like object was passed in, for example a GzipFile, then leave this file open for the caller to close. N)rrrErBrrrgetvalue)rrr2r2r3r9 s zStataWriter._closecCsdS)zNo-op, future compatibilityNr2)rr2r2r3r+ szStataWriter._write_mapcCsdS)zNo-op, future compatibilityNr2)rr2r2r3r8 sz!StataWriter._write_file_close_tagcCsdS)zNo-op, future compatibilityNr2)rr2r2r3r3 sz"StataWriter._write_characteristicscCsdS)zNo-op, future compatibilityNr2)rr2r2r3r6 szStataWriter._write_strlscCs|tdddS)z"Write 5 zeros for expansion fieldsrrN)r r)rr2r2r3r2 sz#StataWriter._write_expansion_fieldscCs&x |jD]}|||jqWdS)N)r r rr)rrr2r2r3r7 s zStataWriter._write_value_labels)rrpr)c CsH|j}|tdd||dkr(dp*d|d|d|t|d|jdd|t|d |jdd |dkr||td d n||t|dd d |dkrt j }nt |t j st d ddddddddddddg }ddt |D}|d||j|d}|||dS)Nrrr\rrr[rrXrPz"time_stamp should be datetime typeJanFebMarAprMayJunJulAugSepOctNovDeccSsi|]\}}||dqS)r(r2)r/rr:r2r2r3  sz-StataWriter._write_header..z%d z %Y %H:%M)rr r~rr rjrl_null_terminate_bytesrr.nowrrGrstrftimer:)rrrprmonths month_lookuptsr2r2r3r* s<      zStataWriter._write_headercCs&x |jD]}|td|qWdS)Nr)rVr r~r)rrSr2r2r3r," s z!StataWriter._write_variable_typescCs:x4|jD]*}||}t|ddd}||qWdS)Nrr)ry_null_terminate_strrr )rrr2r2r3r-& s  zStataWriter._write_varnamescCs"tdd|jd}||dS)Nrr[r()rrjr )rrzr2r2r3r.. szStataWriter._write_sortlistcCs$x|jD]}|t|dqWdS)Nr)r|r r)rrir2r2r3r/3 s zStataWriter._write_formatscCsdx^t|jD]P}|j|rL|j|}||}t|ddd}||q |tddq WdS)Nrrr)rrjr ryr\rr )rrrr2r2r3r08 s    z$StataWriter._write_value_label_namescCstdd}|jdkr6xt|jD]}||q WdSxp|jD]f}||jkr|j|}t|dkrjtdtdd|D}|std|t|dq>||q>WdS)NrrrHz.Variable labels must be 80 characters or fewercss|]}t|dkVqdS)N)r)r/rr2r2r3rR sz5StataWriter._write_variable_labels..zKVariable labels must contain only characters that can be encoded in Latin-1) rrrrjr rrrGr)rblankrrrZ is_latin1r2r2r3r1D s       z"StataWriter._write_variable_labelscCs|S)zNo-op, future compatibilityr2)rrr2r2r3_convert_strls\ szStataWriter._convert_strlsc Cs |j}|j}|j}|jdk rRx4t|D](\}}||kr&t|||j|||<q&W||}i}|jtt j k}xt|D]\}}||}||j kr|| dj t|fd||<d|} | ||<||| ||<qz||j} |s| |j} | ||<qzW|jd|dS)Nr)argsrF)r-Z column_dtypes)rrVr0rrr|r_rr?r@rr%rryrrarPrZ to_records) rrrVr#rrrZnative_byteorderrSstyperPr2r2r3r4` s.       zStataWriter._prepare_data)rBr)cCs||dS)N)r tobytes)rrBr2r2r3r5 szStataWriter._write_data)rr)cCs |d7}|S)Nrr2)rr2r2r3r\ szStataWriter._null_terminate_strcCs|||jS)N)r\rr)rrr2r2r3rV sz!StataWriter._null_terminate_bytes)NTNNNNrN)NN)5rrrrr%rrr#rrrrrr.rrrr rr rrrrrr%rrr!rDr9r+r8r3r6r2r7r*r,r-r.r/r0r1r_r^Zrecarrayr4r5 staticmethodr\rVrr2r2)rGr3r sXQL*E7%2 3  r)rPrrr)cCs|rdS|jtjkr", "<", "little", or "big". default is `sys.byteorder` Notes ----- Supports creation of the StrL block of a dta file for dta versions 117, 118 and 119. These differ in how the GSO is stored. 118 and 119 store the GSO lookup value as a uint32 and a uint64, while 117 uses two uint32s. 118 and 119 also encode all strings as unicode which is required by the format. 117 uses 'latin-1' a fixed width encoding that extends the 7-bit ascii table with an additional 128 characters. rXN)dfr(rZrcCs|dkrtd||_||_||_ddi|_|dkr:tj}t||_d}d}d|_ |dkrjd }d}d |_ n|d krxd }nd }ddd||_ ||_ ||_ dS)N)rXrNrYz,Only dta versions 117, 118 and 119 supportedr)rrr`rzutf-8rXrXzlatin-1rNr\rr[r) rGZ_dta_verrgr( _gso_tabler@rr?rr_o_offet _gso_o_type _gso_v_type)rrgr(rZrZ gso_v_typeZ gso_o_typeZo_sizer2r2r3r s,  zStataStrLWriter.__init__)rr)cCs|\}}||j|S)N)ri)rrrzrr2r2r3 _convert_key szStataStrLWriter._convert_key)r)cs|j}|j}t|j||j}fdd|jD}tj|jtjd}xt| D]|\}\}}xnt|D]b\} \} } || } | dkrdn| } | | d} | dkr| d|df} | || <| | ||| f<qjWqTWx*t|jD]\}} |dd|f|| <qW||fS)a Generates the GSO lookup table for the DataFrame Returns ------- gso_table : dict Ordered dictionary using the string found as keys and their lookup position (v,o) as values gso_df : DataFrame DataFrame where strl columns have been converted to (v,o) values Notes ----- Modifies the DataFrame in-place. The DataFrame returned encodes the (v,o) values as uint64s. The encoding depends on the dta version, and can be expressed as enc = v + o * 2 ** (o_size * 8) so that v is stored in the lower bits and o is in the upper bits. o_size is * 117: 4 * 118: 6 * 119: 5 csg|]}||fqSr2)r-)r/r)r(r2r3r4" sz2StataStrLWriter.generate_table..)rPNrr() rhrgrr(r^emptyrrrZiterrowsgetrl)r gso_tableZgso_dfselectedZ col_indexrridxrowrrrzrrrr2)r(r3generate_table s$   zStataStrLWriter.generate_table)ror)cCst}tdd}t|jdd}t|jdd}|j|j}|j|j}|jd}x|D]\} } | dkrrq`| \} } |||t|| |t|| ||t| d} |t|t | d || ||q`W| d| S) a Generates the binary blob of GSOs that is written to the dta file. Parameters ---------- gso_table : dict Ordered dictionary (str, vo) Returns ------- gso : bytes Binary content of dta file to be placed between strl tags Notes ----- Output format depends on dta version. 117 uses two uint32s to express v and o while 118+ uses a uint32 for v and a uint64 for o. rasciirrrr`)rrzutf-8r() rrr~rrrkrjrrrrr)rrorZgsoZgso_typenullZv_typeZo_typeZlen_typeZstrlZvorzrZ utf8_stringr2r2r3 generate_blob4 s*         zStataStrLWriter.generate_blob)rXN)rrrrr#r rrArrr rlrrsrrvr2r2r2r3rf s &3rfc seZdZdZdZdZd6eeee e e fe ee ee j ee ee e e feee eed fdd Zeee efe ed d d Ze dd ddZd7ee ee j ddddZddddZddddZddddZddddZddddZddddZddd d!Zddd"d#Zddd$d%Z ddd&d'Z!ddd(d)Z"ddd*d+Z#ddd,d-Z$ddd.d/Z%eed0d1d2Z&e'dd3d4d5Z(Z)S)8StataWriter117a A class for writing Stata binary dta files in Stata 13 format (117) Parameters ---------- fname : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary write() functions. If using a buffer then the buffer will not be automatically closed after the file is written. data : DataFrame Input to save convert_dates : dict Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are 'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to 'tc'. Raises NotImplementedError if a datetime column has timezone information write_index : bool Write the index to Stata dataset. byteorder : str Can be ">", "<", "little", or "big". default is `sys.byteorder` time_stamp : datetime A datetime to use as file creation date. Default is the current time data_label : str A label for the data set. Must be 80 characters or smaller. variable_labels : dict Dictionary containing columns as keys and variable labels as values. Each label must be 80 characters or smaller. convert_strl : list List of columns names to convert to Stata StrL format. Columns with more than 2045 characters are automatically written as StrL. Smaller columns can be converted by including the column name. Using StrLs can reduce output file size when strings are longer than 8 characters, and either frequently repeated or sparse. compression : str or dict, default 'infer' For on-the-fly compression of the output dta. If string, specifies compression mode. If dict, value at key 'method' specifies compression mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `fname` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). If dict and compression mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. .. versionadded:: 1.1.0 Returns ------- writer : StataWriter117 instance The StataWriter117 instance has a write_file method, which will write the file to the given `fname`. Raises ------ NotImplementedError * If datetimes contain timezone information ValueError * Columns listed in convert_dates are neither datetime64[ns] or datetime.datetime * Column dtype is not representable in Stata * Column listed in convert_dates is not in DataFrame * Categorical label contains more than 32,000 characters Examples -------- >>> from pandas.io.stata import StataWriter117 >>> data = pd.DataFrame([[1.0, 1, 'a']], columns=['a', 'b', 'c']) >>> writer = StataWriter117('./data_file.dta', data) >>> writer.write_file() Directly write a zip file >>> compression = {"method": "zip", "archive_name": "data_file.dta"} >>> writer = StataWriter117('./data_file.zip', data, compression=compression) >>> writer.write_file() Or with long strings stored in strl format >>> data = pd.DataFrame([['A relatively long string'], [''], ['']], ... columns=['strls']) >>> writer = StataWriter117('./data_file_with_long_strings.dta', data, ... convert_strl=['strls']) >>> writer.write_file() irXNTr) rrr#rrrprrr&rr+c sJg|_| dk r|j| tj||||||||| | d i|_d|_dS)N)rrprrrr+rs)r$extendr.r_map _strl_blob) rrrr#rrrprrr&rr+)rGr2r3r s  zStataWriter117.__init__)rtagr)cCs<t|trt|d}td|dd|td|ddS)zSurround val with zutf-8r]r\zzutf-8releaser\ZMSFZLSFrrNr_r`KrXrNNrHrrrz"time_stamp should be datetime typerIrJrKrLrMrNrOrPrQrRrSrTcSsi|]\}}||dqS)r(r2)r/rr:r2r2r3rU+ sz0StataWriter117._write_header..z%d z %Y %H:%M timestamprheader)rr rrrr|r _dta_versionr~rrjrlrrrr.rWrrGrrXr:rr)rrrprrrZ nobs_sizerZ encoded_labelZ label_sizeZ label_lenrYrZr[Zstata_tsr2r2r3r* sJ      zStataWriter117._write_header)r)cCs|js2d|jjddddddddddddd|_|jj|jdt}x*|jD]}|t |j d|qXW|d| | | ddS)z Called twice during file write. The first populates the values in the map with 0s. The second call writes the final map locations when all blocks have been written. r)Z stata_datamapvariable_typesvarnamessortlistformatsvalue_label_namesrcharacteristicsrstrlsrstata_data_closez end-of-filerrN)ryrErBrrrrHrr~rrr r|r)rrrr2r2r3r+7 s*   zStataWriter117._write_mapcCs\|dt}x&|jD]}|t|jd|qW|d|| | ddS)Nrr_r) r}rrVrr~rrrr r|r)rrrSr2r2r3r,V s    z$StataWriter117._write_variable_typescCs|dt}|jdkrdnd}x@|jD]6}||}t|dd|j|d}||q*W| d| | | ddS)NrrXrrr(r) r}rrryr\rerrrrr r|r)rrZvn_lenrr2r2r3r-^ s    zStataWriter117._write_varnamescCs@|d|jdkrdnd}||d||jdddS)NrrYr[rXrr()r}rr r|rj)rZ sort_sizer2r2r3r.j s zStataWriter117._write_sortlistcCsn|dt}|jdkrdnd}x&|jD]}|t||j|q*W|d| | | ddS)NrrXrrr) r}rrr|rrerrrr r|r)rrZfmt_lenrir2r2r3r/o s   zStataWriter117._write_formatscCs|dt}|jdkrdnd}x\t|jD]N}d}|j|rJ|j|}||}t|dd |j |d}| |q.W| d| ||ddS)NrrXrrrr(r)r}rrrrjr ryr\rerrrrr r|r)rrvl_lenrr encoded_namer2r2r3r0x s     z'StataWriter117._write_value_label_namesc Cs@|dt}|jdkrdnd}td|d}|jdkr|xt|jD]}||qFW|d| | | ddSx|j D]}||jkr|j|}t |dkrtdy||j}Wn4tk r}ztd |j|Wdd}~XYnX|t||dq||qW|d| | | ddS) NrrXrHi@rr(rz.Variable labels must be 80 characters or fewerzDVariable labels must contain only characters that can be encoded in )r}rrrerrrjrrr r|rrrrGrrUnicodeEncodeError) rrrr^rrrr'rr2r2r3r1 s2         z%StataWriter117._write_variable_labelscCs |d||dddS)Nrrs)r}r r|)rr2r2r3r3 s z%StataWriter117._write_characteristicscCs0|d|d|||ddS)Nrss)r}r rb)rrBr2r2r3r5 s  zStataWriter117._write_datacCs"|d|||jddS)Nr)r}r r|rz)rr2r2r3r6 s zStataWriter117._write_strlscCsdS)zNo-op in dta 117+Nr2)rr2r2r3r2 sz&StataWriter117._write_expansion_fieldscCsf|dt}x0|jD]&}||j}||d}||qW|d||| ddS)NrZlblr) r}rr rrr|rrr r)rrrZlabr2r2r3r7 s     z"StataWriter117._write_value_labelscCs(|d|tdd|ddS)Nrz zutf-8z end-of-file)r}r r)rr2r2r3r8 s z$StataWriter117._write_file_close_tagcCs<x6|jD](\}}||jkr |j|}||j|<q WdS)z Update column names for conversion to strl if they might have been changed to comply with Stata naming rules N)rrr$r-)rorignewrqr2r2r3r s  z!StataWriter117._update_strl_names)rr)csJfddt|D}|rFt||jd}|\}}|}||_|S)zg Convert columns to StrLs if either very large or in the convert_strl variable cs,g|]$\}}j|dks$|jkr|qS)i)rVr$)r/rr)rr2r3r4 sz1StataWriter117._convert_strls..)rZ)rrfrrsrvrz)rrZ convert_colsZsswtabZnew_datar2)rr3r_ s    zStataWriter117._convert_strls)rr)cCsng|_g|_x\|D]P\}}||jk}t||j||j|d}|j||jt||j||qWdS)N)rr) rVr|rr$rrrrrd)rrrrPrrir2r2r3r s  z%StataWriter117._set_formats_and_types) NTNNNNNrN)NN)*rrrrr%rrr#rrrrrr.r rrrrcr rr|r}r*r+r,r-r.r/r0r1r3r5r6r2r7r8rr_r%rrr2r2)rGr3rwu sDTV7  "  rwcseZdZdZdZd eeeee e fe ee ee j ee eee e fee e eeeed fdd Ze e d d d ZZS) StataWriterUTF8ub Stata binary dta file writing in Stata 15 (118) and 16 (119) formats DTA 118 and 119 format files support unicode string data (both fixed and strL) format. Unicode is also supported in value labels, variable labels and the dataset label. Format 119 is automatically used if the file contains more than 32,767 variables. .. versionadded:: 1.0.0 Parameters ---------- fname : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or object implementing a binary write() functions. If using a buffer then the buffer will not be automatically closed after the file is written. data : DataFrame Input to save convert_dates : dict, default None Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are 'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name. Datetime columns that do not have a conversion type specified will be converted to 'tc'. Raises NotImplementedError if a datetime column has timezone information write_index : bool, default True Write the index to Stata dataset. byteorder : str, default None Can be ">", "<", "little", or "big". default is `sys.byteorder` time_stamp : datetime, default None A datetime to use as file creation date. Default is the current time data_label : str, default None A label for the data set. Must be 80 characters or smaller. variable_labels : dict, default None Dictionary containing columns as keys and variable labels as values. Each label must be 80 characters or smaller. convert_strl : list, default None List of columns names to convert to Stata StrL format. Columns with more than 2045 characters are automatically written as StrL. Smaller columns can be converted by including the column name. Using StrLs can reduce output file size when strings are longer than 8 characters, and either frequently repeated or sparse. version : int, default None The dta version to use. By default, uses the size of data to determine the version. 118 is used if data.shape[1] <= 32767, and 119 is used for storing larger DataFrames. compression : str or dict, default 'infer' For on-the-fly compression of the output dta. If string, specifies compression mode. If dict, value at key 'method' specifies compression mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `fname` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). If dict and compression mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. .. versionadded:: 1.1.0 Returns ------- StataWriterUTF8 The instance has a write_file method, which will write the file to the given `fname`. Raises ------ NotImplementedError * If datetimes contain timezone information ValueError * Columns listed in convert_dates are neither datetime64[ns] or datetime.datetime * Column dtype is not representable in Stata * Column listed in convert_dates is not in DataFrame * Categorical label contains more than 32,000 characters Examples -------- Using Unicode data and column names >>> from pandas.io.stata import StataWriterUTF8 >>> data = pd.DataFrame([[1.0, 1, 'ᴬ']], columns=['a', 'β', 'ĉ']) >>> writer = StataWriterUTF8('./data_file.dta', data) >>> writer.write_file() Directly write a zip file >>> compression = {"method": "zip", "archive_name": "data_file.dta"} >>> writer = StataWriterUTF8('./data_file.zip', data, compression=compression) >>> writer.write_file() Or with long strings stored in strl format >>> data = pd.DataFrame([['ᴀ relatively long ŝtring'], [''], ['']], ... columns=['strls']) >>> writer = StataWriterUTF8('./data_file_with_long_strings.dta', data, ... convert_strl=['strls']) >>> writer.write_file() zutf-8NTr) rrr#rrrprrr&rZrr+c s|| dkr |jddkrdnd} n0| dkr2tdn| dkrP|jddkrPtdtj||||||||| | | d | |_dS) Nr(irNrY)rNrYz"version must be either 118 or 119.zKYou must use version 119 for data sets containing more than32,767 variables) r#rrrprrr&rr+)rrGr.rr) rrrr#rrrprrr&rZrr+)rGr2r3r_ s( zStataWriterUTF8.__init__)rr)cCs~xx|D]p}t|dkrN|dks&|dkrN|dks6|dkrN|dksF|dkrN|dksjdt|krfd krnq||d}qW|S) a Validate variable names for Stata export. Parameters ---------- name : str Variable name Returns ------- str The validated name with invalid characters replaced with underscores. Notes ----- Stata 118+ support most unicode characters. The only limitation is in the ascii range where the characters supported are a-z, A-Z, 0-9 and _. rrrrrrrrr])rr)rrrr2r2r3r s  z'StataWriterUTF8._validate_variable_name) NTNNNNNNrN)rrrrrrr#rrrrrr.r rArrrrrr2r2)rGr3r sb\r) TTNFTNTNFN)rF)lr collectionsrr.iorr;r~r@typingrrrrrr r r r reZdateutil.relativedeltar Znumpyr^Zpandas._libs.librZpandas._libs.writersrZpandas._typingrrrrrZpandas.util._decoratorsrrZpandas.core.dtypes.commonrrrZpandasrrrrrrr r!Z pandas.corer"Zpandas.core.framer#Zpandas.core.indexes.baser$Zpandas.core.seriesr%Zpandas.io.commonr&riZ_statafile_processing_params1Z_statafile_processing_params2Z_chunksize_paramsZ_iterator_paramsZ _reader_notesZ_read_stata_docrrrrdrkrrrWarningrrrrrrrrrrrrIteratorr!rrArr?rrPrrrrZ _shared_docsrrdrrerfrwrr2r2r2r3 s  ,   (      ,$#k  Yn#p(  %+* 7