/usr/local/lib64/python3.6/site-packages/pandas/io/__pycache__
NameSizeModeActions
api.cpython-36.pyc10960644editdlrm
clipboards.cpython-36.pyc33920644editdlrm
common.cpython-36.pyc140640644editdlrm
date_converters.cpython-36.pyc19470644editdlrm
feather_format.cpython-36.pyc29360644editdlrm
gbq.cpython-36.pyc74590644editdlrm
html.cpython-36.pyc319770644editdlrm
orc.cpython-36.pyc18020644editdlrm
parquet.cpython-36.pyc95000644editdlrm
parsers.cpython-36.pyc882000644editdlrm
pickle.cpython-36.pyc56790644editdlrm
pytables.cpython-36.pyc1308050644editdlrm
spss.cpython-36.pyc13280644editdlrm
sql.cpython-36.pyc522830644editdlrm
stata.cpython-36.pyc975630644editdlrm
__init__.cpython-36.pyc1450644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/pandas/io/__pycache__/stata.cpython-36.pyc (97563B)
3 :%Eg@sdZddlmZddlZddlmZmZddlZddlm Z ddl Z ddl Z ddl m Z mZmZmZmZmZmZmZmZmZddlZddlmZddlZddlmZdd lmZdd l m!Z!m"Z"dd l#m$Z$dd l%m&Z&m'Z'm(Z(dd l)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5ddl6m7Z7ddl8m9Z9m:Z:m;Z;mdZ?dZ@dZAdZBdZCde?de@deAdeBdeCd ZDde?de@dZEde?de@deAdeCd ZFd d!d"d#d$d%d&d'd(g ZGejd)d*d*ZHe7d+d,d-ZIe7eJe7d.d/d0ZKd1ZLGd2d3d3eMZNd4ZOGd5d6d6eMZPd7ZQGd8d9d9eMZRd:ZSGd;d<dd?d@ZVGdAdBdBZWGdCdDdDZXGdEdFdFZYGdGdHdHeYejZZ[e$eDdqe!e\e\eeJe\e\eeeJe\ee]e\ee3e[fdK dLdMZ^e!eeJeeJeJfdfeee\eeeJeeJeJfffdNdOdPZ_eJeJdQdRdSZ`ee]edTdUdVZaeJejbdWdXdYZceee"edZd[d\Zdejbe7e]d]d^d_Zedre7e]e\eJdadbdcZfGdddedeeYZgejbe7e\e]dfdgdhZheeJeife]eidTdidjZjGdkdldlZkGdmdndnegZlGdodpdpelZmdS)sa 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)BytesIOIOBase)Path) AnyAnyStrBinaryIODictListMappingOptionalSequenceTupleUnion) relativedelta) infer_dtype)max_len_string_array)FilePathOrBufferLabel)Appender) ensure_objectis_categorical_dtypeis_datetime64_dtype) Categorical DatetimeIndexNaT Timestampconcatisna to_datetime to_timedelta) DataFrame)Index)Series)get_compression_methodget_filepath_or_buffer get_handleinfer_compressionstringify_pathzVersion 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 handler (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 a"Class 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. .. versionadded:: 0.23.0 support for pathlib, py.path. z z%tcz%tCz%tdz%dz%twz%tmz%tqz%thz%tyi)returncsftjjtjjtjtjdddjtjtjdddjddddddtdfdd }tdfd d }tdfd d }tj|}d }|j rd}t|}d||<|j tj }|j d.rt }|} ||| d} n^|j d/r*tjdt|td} |r&t| |<| S|j d0rNt }|} ||| d} n|j d1rt j|d} |dd} || | } n|j d2rt j|d!} |d!d} || | } n|j d3rt j|d$} |d$d%d}|| |} nl|j d4rt j|d(} |d(d)d} || | } n6|j d5rD|} tj|}|| |} ntd,|d-|rbt| |<| S)6a 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|jkr,|jkr,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|]\}}tj||dqS)r*)datetime).0ymr4;/usr/local/lib64/python3.6/site-packages/pandas/io/stata.py szX_stata_elapsed_date_to_datetime_vec..convert_year_month_safe..)r/)maxminrgetattrr#zip)yearmonthr/)MAX_YEARMIN_YEARr4r5convert_year_month_safes  zD_stata_elapsed_date_to_datetime_vec..convert_year_month_safecsd|jdkr4|jkr4t|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|]$\}}tj|ddtt|dqS)r*)days)r0rint)r1r2r@r4r4r5r6szW_stata_elapsed_date_to_datetime_vec..convert_year_days_safe..)r/)r7r8rr r9r:r#)r;rBr/value)r=r>r4r5convert_year_days_safes  zC_stata_elapsed_date_to_datetime_vec..convert_year_days_safecst|dd}|dkrL|jks,|jkrfdd|D}t||dSnH|dkr|jksl|jkrfdd|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))rB)rrC)r1r@)baser4r5r6&szS_stata_elapsed_date_to_datetime_vec..convert_delta_safe..)r/mscs"g|]}tt|ddqS)i) microseconds)rrC)r1r@)rFr4r5r6+szformat not understood)rA)r9r7r8r# ValueErrorrr )rFZdeltasrAr/values) MAX_DAY_DELTA MAX_MS_DELTA MIN_DAY_DELTA MIN_MS_DELTA)rFr5convert_delta_safes  z?_stata_elapsed_date_to_datetime_vec..convert_delta_safeFTg?%tctcrG%tCtCz9Encountered %tC format. Leaving in Stata Internal Format.)dtype%tdtd%dr@%twtw4%tmtm %tqtq%thth%tytyz Date fmt z not understood)rPrQ)rRrS)rUrVrWr@)rXrY)r\r])r_r`)rcrd)rgrh)rr8r;r7r0rBr#npisnananyastypeint64 startswith stata_epochwarningswarnobjectrZ ones_likerI)datesfmtr?rErOZbad_locsZhas_bad_valuesZdata_colrFrG conv_datesrBr;r<Z quarter_monthZ first_monthr4)rKrLr=rMrNr>r5#_stata_elapsed_date_to_datetime_vecsj.                    rv)rsrtr+cs|jd.dd/fdd }t|}|j|jr`t|}t|rXtt||<nt||<|d0kr||d d }|jd}n>|d1krtj d |}n$|d2kr||d d }|j}n|d3kr||d d d}d|j tj |j d}n|d4kr$||d d}d|j tj |j d}n|d5krZ||d d}d|j tj |j dd}nf|d6kr||d d}d |j tj |j d!kj t}n.|d7kr||d d}|j }ntd$|d%t|tjd&}tjd'd(d)}|||<t|d*S)8aX 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 r,iiFc sRi}t|jr|r0|t}|jjtjd|d<|s8|rTt|}|j|d<|j |d<|r|jtjt |dddjtj}||d<nt |dd d kr>|r|jt}t j td fd d }tj|} | ||d<|r|jdd} | jd|d<| j|dd|d<|rFt j td dd} tj| } | ||d<ntdt|dS)Nideltar;r<z%Y)r.rBF)skipnar0)xr+cs|jd|j|jS)Ni@B)rBsecondsrH)ry) US_PER_DAYr4r5fszC_datetime_to_stata_elapsed_vec..parse_dates_safe..fcSsd|j|jS)Nr-)r;r<)ryr4r4r5szJ_datetime_to_stata_elapsed_vec..parse_dates_safe..r-cSs|tj|jddjS)Nr*)r0r;rB)ryr4r4r5gszC_datetime_to_stata_elapsed_vec..parse_dates_safe..gzZColumns containing dates must contain either datetime64, datetime.datetime or null values.)r/)rrTro_valuesrlrirmrr;r<rrr0 timedeltafloatZ vectorizeapplyrCrIr!) rsrwr;rBr@Z time_deltaZ date_indexZ days_in_nsr|vZ year_monthr~) NS_PER_DAYr{r/r4r5parse_dates_safe}s>         z8_datetime_to_stata_elapsed_vec..parse_dates_safe%tcrQT)rw%tCrSz'Stata Internal Format tC not supported.%tdrV%twrY)r;rBrZr[%tmr])r;r^r*%tqr`rarb%thrdrerf%tyrhzFormat z! is not a known Stata date format)rTz.)keyrr*i}zaStata value labels for a single variable must have a combined length less than 32,000 characters.)rTra)rr)rInamelabname _encodingcat categorieslistr:riarangelen value_labelssorttext_lentxtn isinstancestrrprqvalue_label_mismatch_docr.rencodeappendarrayroffval)selfrrroffsetsrJvlcategoryr4r4r5__init__ts>       zStataValueLabel.__init__) byteorderr+c Cs:|j}t}d}|jtj|d|jt|jddj|}|d krLdnd}t ||d}|j|x"t d D]}|jtjd |qrW|jtj|d|j |jtj|d|j x$|j D]}|jtj|d|qWx$|jD]} |jtj|d| qWx|jD]} |j| |qW|jd |jS) 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 utf-8utf8r*rbcr)rr)rrwriterpackrrrr _pad_bytesrangerrrrrseekread) rrrbio null_byterZlab_lenroffsetrDtextr4r4r5generate_value_labels(     z$StataValueLabel.generate_value_labelN)r) rrr__doc__r#rrbytesrr4r4r4r5rhs ,rc@s,eZdZUdZiZeeefd&Zx@eD]8Z dee <x*e ddD]Z de de ee e <q@Wq(Wd Z ejd d d Zxpe dD]dZ ejd e d Zdee<e d kreee de 7<ejd ejd ed eZejd eZ qWdZejddd Zxte dD]hZ ejded Zdee<e d krFeee de 7<ejdejded eZejdeZqWdddejd e d ejded dZeeefdddZeedddZeeeefdddZedddZedddZeedd 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 e.r*`szszStataMissingValue.__str__cCst|d|dS)N(r)type)rr4r4r5__repr__AszStataMissingValue.__repr__)otherr+cCs&t|t|o$|j|jko$|j|jkS)N)rrrrD)rrr4r4r5__eq__Ds zStataMissingValue.__eq__)rTr+cCsz|tjkr|jd}n`|tjkr,|jd}nJ|tjkrB|jd}n4|tjkrX|jd}n|tjkrn|jd}ntd|S)NrrrrrzUnsupported dtype)rirBASE_MISSING_VALUESrrrrrI)clsrTrDr4r4r5get_base_missing_valueKs          z(StataMissingValue.get_base_missing_valueN)rrr)%rrrrrr rrbasesbrrchrZ float32_baserr incrementrrZ int_valueZ float64_baserrrCrpropertyrrDrrrboolr classmethodrirTrr4r4r4r5rsP #     rc@seZdZddZdS) StataParserc<CsttttddddtddDdtjtjfdtjtjfdtjtjfdtjtj fd tjtj fg|_ td tjtj fd tjtj fd tjtj fd tjtjfdtjtjfdtjtjfg|_ ttdtd|_tdndodpdqdrdsg|_d}d}d}d}dudwdytj tjd!|d"tj tjd!|d"ftj tjd#|d"tj tjd#|d"fd$|_ddddd d%|_d&d'd(tj tjd!d)d"tj tjd#d*d"d$|_d+d,d-d.d/d0d1|_dz|_dS){Nr*cSsg|]}tjdt|qS)a)rirTr)r1rr4r4r5r6osz(StataParser.__init__..ZbhlfdQr@r|lhrss~ssrr-iizr?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrR)dictrr:rrirTrrrrr DTYPE_MAPr DTYPE_MAP_XMLTYPE_MAP TYPE_MAP_XMLrr VALID_RANGEOLD_TYPE_MAPPINGrNUMPY_TYPE_MAPRESERVED_WORDS)rZ float32_minrZ float64_minrr4r4r5r]s"   zStataParser.__init__N)rrrrr4r4r4r5r\src seZdZeZdPeeeeeeeee eeee d fdd Z dddd Z ddd d Z ddd d ZddddZddddZddddZe eeee efeeeejffdddZeedddZeedddZeedddZeedddZe ddd Zedd!d"Zedd#d$Ze dd%d&Ze dd'd(d)Z!ejdd*d+Z"ee efe d,d-d.Z#e ed/d0d1Z$ddd2d3Z%ddd4d5Z&e'dd6d7Z(dQee e'd8d9d:Z)e*e+dRee eeeeeeeeeeee eeee'd; dd?d@Z-e'e'dAdBdCZ.e'e ee'dDdEdFZ/e'e0ee0ee1e feffe eee'dGdHdIZ2e3eddJdKZ4e0eefddLdMZ5e0ee0ee1e feffddNdOZ6Z7S)S StataReaderTNF) path_or_buf convert_datesconvert_categoricals index_colconvert_missingpreserve_dtypescolumnsorder_categoricals chunksizec s&tjg|_||_||_||_||_||_||_||_ d|_ | |_ d|_ |j dkr^d|_ nt | t sr| dkrztdd|_d|_d|_d|_d|_d|_d|_d|_ttj|_t|}t |trt|\}} } } t |ttfrt |d|_!nt |t"r|j#} t$| |_!|j%|j&dS)NrFr*rz.chunksize must be a positive integer when set.rb)'superr col_sizes_convert_dates_convert_categoricals _index_col_convert_missing_preserve_dtypes_columns_order_categoricalsr _chunksize_using_iteratorrrCrIZ_has_string_dataZ_missing_values_can_read_value_labels_column_selector_set_value_labels_read _data_read_dtype _lines_read_set_endiannesssysr_native_byteorderr(rr%ropenr`rrr _read_header _setup_dtype)rr`rarbrcrdrerfrgrhr_Z should_closecontents) __class__r4r5rsF      zStataReader.__init__)r+cCs|S)z enter context manager r4)rr4r4r5 __enter__<szStataReader.__enter__cCs |jdS)z exit context manager N)close)rexc_type exc_value tracebackr4r4r5__exit__@szStataReader.__exit__c Cs(y|jjWntk r"YnXdS)z close the handle if its open N)r`rIOError)rr4r4r5rDszStataReader.closecCs|jdkrd|_nd|_dS)zC Set string encoding which depends on file version vzlatin-1zutf-8N)format_versionr)rr4r4r5 _set_encodingKs zStataReader._set_encodingcshjjd}tjd|ddkr*jn j|tddjDdk_fddjD_ dS)Nr*rr.csg|]}j|qSr4) _calcsize)r1typ)rr4r5r6^s) r`rrr_read_new_header_read_old_headerrtyplistZhas_string_datark)r first_charr4)rr5rTs    zStataReader._read_headercCs|jjdt|jjd|_|jdkr:ttj|jd|j|jjd|jjddkrbd pdd |_|jjd |jdkrd nd }|jdkrdnd}t j |j||jj|d|_ |jjd|j |_ |jjd|j|_|jjd|j|_|jjd|jjd|jjdt j |jd|jjddd|_t j |jd|jjddd|_t j |jd|jjddd|_t j |jd|jjddd|_t j |jd|jjddd|_|j|_|jjdt j |jd|jjddd|_t j |jd|jjddd|_t j |jd|jjddd|_|j|j\|_|_|jj|j|j |_!|jj|jt j |jd|j d|jjd|j ddd|_"|jj|j|j#|_$|jj|j|j%|_&|jj|j|j'|_(dS) Nrrburw)versionsMSF><HIrerarr[ rr rfrr*)rrr))r`rrCrrI_version_errorr.rrrrnvar _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_dtypesrdtyplistr _get_varlistvarlistsrtlist _get_fmtlistfmtlist _get_lbllistlbllist_get_variable_labels_variable_labels)r nvar_typeZ nvar_sizer4r4r5r`s\             $$$$$  $$$    zStataReader._read_new_header) seek_vartypesr+csjj|fddtjD}ttttfdfdd fdd|D}ttttjfdfdd fd d|D}||fS) Ncs*g|]"}tjjdjjddqS)rrer)rrrr`r)r1r)rr4r5r6sz+StataReader._get_dtypes..)rr+csP|dkr |Sy j|Stk rJ}ztd|d|WYdd}~XnXdS)Nizcannot convert stata types [])rZKeyErrorrI)rerr)rr4r5r|s  z"StataReader._get_dtypes..fcsg|] }|qSr4r4)r1ry)r|r4r5r6scsT|dkrt|Sy j|Stk rN}ztd|d|WYdd}~XnXdS)Nizcannot convert stata dtype [r)rrXrrI)rr)rr4r5r~s  z"StataReader._get_dtypes..gcsg|] }|qSr4r4)r1ry)r~r4r5r6s) r`rrrrCrrrirT)rrZ raw_typlistrrr4)r|r~rr5rs  zStataReader._get_dtypescs,jdkrdndfddtjDS)Nr!csg|]}jjjqSr4)_decoder`r)r1r)rrr4r5r6sz,StataReader._get_varlist..)rrr)rr4)rrr5rszStataReader._get_varlistcsNjdkrdn$jdkr dnjdkr0dndfdd tjDS) Nr9q1hr^r[csg|]}jjjqSr4)rr`r)r1r)rrr4r5r6sz,StataReader._get_fmtlist..)rrr)rr4)rrr5rs   zStataReader._get_fmtlistcs>jdkrdnjdkr dndfddtjDS)Nrrrrrcsg|]}jjjqSr4)rr`r)r1r)rrr4r5r6sz,StataReader._get_lbllist..)rrr)rr4)rrr5rs   zStataReader._get_lbllistcsdjdkr$fddtjD}n<jdkrHfddtjD}nfddtjD}|S)Nrcsg|]}jjjdqS)iA)rr`r)r1r)rr4r5r6sz4StataReader._get_variable_labels..rcsg|]}jjjdqS)Q)rr`r)r1r)rr4r5r6scsg|]}jjjdqS)r)rr`r)r1r)rr4r5r6s)rrr)rZvlblistr4)rr5rs   z StataReader._get_variable_labelscCsJ|jdkr(tj|jd|jjddStj|jd|jjddSdS)Nrr rrrra)rrrrr`r)rr4r4r5rs zStataReader._get_nobscCs|jdkr:tj|jd|jjdd}|j|jj|S|jdkrntjd|jjdd}|j|jj|S|jdkr|j|jjd S|j|jjd SdS) Nrrrerrrr*rrr)rrrrr`rr)rstrlenr4r4r5rs   zStataReader._get_data_labelcCs|jdkr4tjd|jjdd}|jj|jdS|jdkrhtjd|jjdd}|j|jj|S|jdkr|j|jjdStdS) Nrrr*rzutf-8rr)rrrr`rdecoderrI)rrr4r4r5r s   zStataReader._get_time_stampcCsd|jdkr.|jjd|jd|jddS|jdkrZtj|jd|jjdddStdS) Nrrrrrr) rr`rrrrrrrI)rr4r4r5rs    "z%StataReader._get_seek_variable_labels)rr+c "sFtjd|d_jd"kr.ttjjd jtjdjjd dd krVd pXd _ tjdjjd d_ jjd tjj djjdd_ j _ j_j_jdkrfddtj D}n^jjj }tj|tjd}g}x:|D]2}|jkr.|jj|n|j|dq Wyfdd|D_WnJtk r}z,djdd|D}td|d|WYdd}~XnXyfdd|D_WnJtk r}z,djdd|D}td|d|WYdd}~XnXjdkr2fddtj D_nfddtj D_tjj dj d jjdj d dd#_j_j_ j!_"jdkr6xtjj djjd d} jdkrtjj d jjd!d} ntjj djjdd} | dkr$Pjj| qWjj#_$dS)$Nrrrrrorrs)rr*rrrrecsg|]}tjjdqS)r*)ordr`r)r1r)rr4r5r66sz0StataReader._read_old_header..)rTrcsg|]}j|qSr4)rY)r1r)rr4r5r6Bs,css|]}t|VqdS)N)r)r1ryr4r4r5 Dsz/StataReader._read_old_header..zcannot convert stata types [rcsg|]}j|qSr4)rW)r1r)rr4r5r6Gscss|]}t|VqdS)N)r)r1ryr4r4r5rIszcannot convert stata dtypes [csg|]}jjjdqS)r)rr`r)r1r)rr4r5r6Nscsg|]}jjjdqS)r)rr`r)r1r)rr4r5r6Rsrrra)rrrrrrrr)%rrrrIrr.rr`rrZfiletyperrrrrrrrri frombufferrr\rrjoinrrrrrrrrrtellr) rrrbufZtyplistbtprZ invalid_typesZinvalid_dtypesZ data_typeZdata_lenr4)rr5r"sp &        $$        zStataReader._read_old_headercCs|jdk r|jSg}xbt|jD]T\}}||jkrV|jdt||j|j|fq |jdt|dt|fq Wtj||_|jS)z"Map between numpy and state dtypesNsS) ry enumeraterr]rrrrirT)rdtypesrrr4r4r5rxs  $" zStataReader._setup_dtype)rtr+cCst|tr|Stj|j|S)N)rrCrcalcsizer)rrtr4r4r5rs zStataReader._calcsize)rr+c CsX|jdd}y |j|jStk rR|j}d|d}tj|t|jdSXdS)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) partitionrrUnicodeDecodeErrorrprqUnicodeWarning)rrrmsgr4r4r5rs   zStataReader._decodec Cs|jr dS|jdkr$d|_i|_dS|jdkr>|jj|jn.|jdk sLt|j|jj }|jj|j |d|_i|_x|jdkr|jj ddkrP|jj d}|sP|jdkr|j |jj d}n|j |jj d}|jj d t j|jd |jj dd }t j|jd |jj dd }tj|jj d||jd |d }tj|jj d||jd |d }tj|}||}||}|jj |} t|j|<xTt|D]H} | |dkr|| dn|} |j | || | |j||| <qW|jdkr||jj dq|Wd|_dS)NrTrs|j?|}|sg}d}x|D]}||j2} | tj2tj@tj2tjAfkrftj2tjB} d}n8| tj2tjCtj2tjDtj2tjEfkrtj2tjF} d}|j4|||jG| fq(W|rtj6t7|}|dk r|j%|jH|}|S)NrT)rfr)rTr)Z convert_dtypeF)ryr+cstfddtDS)Nc3s|]}j|VqdS)N)rn)r1rt)ryr4r5rsz;StataReader.read..any_startswith..)rk _date_formats)ryr4)ryr5any_startswithsz(StataReader.read..any_startswithcsg|] }|qSr4r4)r1ry)rr4r5r6sz$StataReader.read..r)Irrurxrr!rrlrmrorprqrrrnrrwrryrrzrr8r StopIterationr`rrrirrrr}byteswap newbyteorderrZ from_recordsrfrZ set_index_do_select_columnsrIr:rrrCrr _insert_strlswhererr/rTrrrr# from_dictrV_do_convert_missingrrrrv_do_convert_categoricalsrrZfloat16rrrrrrmrlpop)rrrarbrcrdrerfrgrTZ max_read_lenZread_lenr read_linesrixrrZcols_Zrequires_type_conversiondata_formattedrcolsZ retyped_dataconvertr4)rr5rs                         zStataReader.read)rrdr+cCsHi}xt|D]\}}|j|}||jkr.q|j|\}}||} tj| |k| |k} | jsbq|rtjtj| d} tj| | dd\} } t | t d}xft| D]&\}}t |}| | |k}||j |<qWn2| j }|tjtjfkrtj}t | |d}tj|| <|||<qW|rD|j}t|}t|j|jd|gd}||}|S)NrT)Zreturn_inverse)rTr*)rrr[ri logical_orrkZnonzeroZasarrayuniquer#rrrilocrTrrnanrfr!rZdrop)rrrd replacementsrZcolnamertZnminZnmaxZseriesmissingZ missing_locZumissingZ umissing_loc replacementjZumrlocrTrfZreplacement_dfZreplacedr4r4r5rs<       zStataReader._do_convert_missing)rr+csrtd stjdkr|SxNtjD]@\}}|dkr.)hasattrrrrrr )rrrrr4)rr5rs2zStataReader._insert_strls)rrfr+c Cs|jst|}t|t|kr&td|j|j}|rRdjt|}td|g}g}g}g} xX|D]P} |jj| } |j |j | |j |j | |j |j | | j |j | qhW||_ ||_ ||_ | |_ d|_||S)Nz"columns contains duplicate entriesz, z|j D]&}|| kr|j| |q|j|qWn t| j}y ||_ Wnttk r`}zVt|j}t|j|dk}ddddj|}d|d|d}t||WYdd}~XnXt||jd }|j||fq|j|||fqWtjt|}|S) zC Converts categorical columns to Categorical type. N)rZorderedr*-Pr)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/)rkeysr:ririsinrtallrprqcategorical_conversion_warningrrrrrJrIr#Z value_countsr/rr!rrV)rrrrrgrZcat_converted_datarlabelrrcolumnZ key_matchesZinitial_categoriesZcat_datarrrZvcZ repeated_catsZrepeatsrZ cat_seriesr4r4r5rsH         z$StataReader._do_convert_categoricalscCs|jS)z2 Return data label of Stata file. )r)rr4r4r5 data_labelKszStataReader.data_labelcCstt|j|jS)z Return variable labels as a dict, associating each variable name with corresponding label. Returns ------- dict )rVr:rr)rr4r4r5variable_labelsRs zStataReader.variable_labelscCs|js|j|jS)z Return a dict, associating each variable name a dict, associating each value its corresponding label. Returns ------- dict )rwrr)rr4r4r5r]s zStataReader.value_labels)TTNFTNTN)N)NNNNNNNN)8rrr_stata_reader_docrrrr rr rCrrrrrrrrr rrirTrrrrrrrrrrrrrrrrr!rrr_read_method_docrrrrr rrrrrr __classcell__r4r4)rr5r_sp4/  N0     V66& #D r_TF) filepath_or_bufferrarbrcrdrerfrgrhiteratorr+c CsBt|||||||||d } | s"|r&| Sz | j} Wd| jX| S)N)rarbrcrdrerfrgrh)r_rr) r"rarbrcrdrerfrgrhr#readerrr4r4r5 read_statals   r%)fname compressionr+cCst|dr|ddfSt|ttfrt|\}}t||}t||d\}}}}|dk rb|}||d<nd}t|d|dd\}}|d|fStd dS) a Open a binary file or no-op if file-like. Parameters ---------- fname : string path, path object or buffer The file name or buffer. compression : {str, dict, None} The compression method to use. Returns ------- file : file-like object File object supporting write own : bool True if the file was created, otherwise False rFN)r'methodwb)r'Zis_textTz1fname must be a binary file, buffer or path-like.) rrrrr$r'r%r& TypeError)r&r'Zcompression_typZcompression_argsr`rr|r4r4r5_open_file_binary_writes      r+) endiannessr+cCs4|jdkrdS|jdkr dStd|ddS) Nrlittlerbigz Endianness z not understood)rr-)rr.)lowerrI)r,r4r4r5r{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)rrr4r4r5rs r)rtr+cCs(|dkrtjtjStd|ddS)zK Convert from one of the stata date formats to a type in TYPE_MAP. rQ%tcrV%tdrY%twr]%tmr`%tqrd%thrh%tyzFormat z not implementedN)rQr1rVr2rYr3r]r4r`r5rdr6rhr7)rirTrNotImplementedError)rtr4r4r5_convert_datetime_to_stata_types" r9)rarr+cCszi}xp|D]h}||jds,d||||<||krN|j|j|||iq t|ts`td|j|||iq W|S)N%z0convert_dates key must be a column or an integer)rnupdater/rrCrI)rarZnew_dictrr4r4r5_maybe_convert_to_int_keyss  r<)rTrr+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) rriobject_rrrr7rrrrrr8)rTrrr4r4r5_dtype_to_stata_types       r>r)r dta_version force_strlr+cCs|dkrd}n d}|rdS|jtjkrntt|j}||krX|dkrHdSttj|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" riz%9sr:r*rz%10.0gz%9.0gz%12.0gz%8.0gz Data type z not supported.N)rrir=rrrrIexcessive_string_length_errorr.rrr7rrrrrr8)rTrr?r@ max_str_lenrr4r4r5_dtype_to_default_stata_fmts*    rDcsLeZdZdZdZdZdOeeee e e fe ee ee j ee ee e e fee ee e fdfd 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. .. versionadded:: 0.23.0 support for pathlib, py.path. 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 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() rAzlatin-1NTinfer) r&rra write_indexrrrrr'c stj|dkrin||_||_||_||_||_d|_| |_d|_ |j ||dkr^t j }t ||_t||_tjtjtjd|_i|_d|_dS)NT)rrr)rjrrl _write_index _time_stamprr _own_file _compression _output_file_prepare_pandasr|rr{ _byteorderr(_fnamerirrrZtype_converters_converted_names_file) rr&rrarGrrrrr')rr4r5rs"    zStataWriter.__init__)to_writer+cCs&|jdk st|jj|j|jdS)zS Helper to call encode before writing to file for Python 3 compat. N)rQrrrr)rrRr4r4r5_writeszStataWriter._write)rDr+cCs|jdk st|jj|dS)z? Helper to assert file is open before writing. N)rQrr)rrDr4r4r5 _write_bytesszStataWriter._write_bytes)rr+c s*fddD}||_g|_t|s*Stj}g}xt|D]\}}|rt||jd}|jj||j j j }|t j krtd|j j jj} | j||kr|t jkrt j}n|t jkrt j}nt j}t j| |d} ||| | dk<|j|| fq@|j||fq@Wtjt|S)z Check for categorical columns, retain categorical information for Stata file and convert categorical data to int csg|]}t|jqSr4)rrT)r1r)rr4r5r6sz5StataWriter._prepare_categoricals..)rzCIt is not possible to export int64-based categorical data to Stata.)rTr*r) _is_col_cat _value_labelsrkrrr:rrrrcodesrTrirmrIrcopyr7rrrrrr!rrV) rrZis_catrrrZ col_is_catZsvlrTrJr4)rr5_prepare_categoricalss6    z!StataWriter._prepare_categoricalscCs^xX|D]P}||j}|tjtjfkr|tjkr:|jd}n |jd}||j|||<qW|S)z Checks floating point data columns for nans, and replaces these with the generic Stata for missing value (.) r|r@)rTrirrrfillna)rrrrTr r4r4r5 _replace_nanss     zStataWriter._replace_nans)r+cCsdS)zNo-op, forward compatibilityNr4)rr4r4r5_update_strl_names szStataWriter._update_strl_names)rr+cCsVxP|D]H}|dks|dkr|dks*|dkr|dks:|dkr|dkr|j|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)rrrr4r4r5_validate_variable_name s z#StataWriter._validate_variable_namecCsi}t|j}|dd}d}xt|D]\}}|}t|tsFt|}|j|}||jkrbd|}d|dkoxdknrd|}|dtt|d}||ksx@|j |dkrdt||}|dtt|d}|d7}qW|||<|||<q(Wt ||_|j rHx:t ||D],\} } | | kr|j | |j | <|j | =qW|rg} x.|j D]"\}}|d|} | j| q\Wtjd j| } tj| t||_|j|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 Nrrrr`rr*z -> z )rrfrrrrbr^r8rrr"rlr:itemsrinvalid_name_docr.rrprqrrPr\)rrZconverted_namesrfZoriginal_columnsZduplicate_var_idrr orig_nameroZconversion_warningrrr4r4r5_check_column_names" sJ           zStataWriter._check_column_names)rr+cCsVg|_g|_xD|jD]8\}}|jjt||j||jjt||j|qWdS)N)rrrcrrDrr>)rrrrTr4r4r5_set_formats_and_typesg s z"StataWriter._set_formats_and_typescCs,|j}|jr$|j}t|tr$|}|j|}t|}|j|}|j|}|j \|_ |_ ||_ |j j|_|j}x.|D]&}||jkrqvt||rvd|j|<qvWt|j|j|_x*|jD] }t|j|}tj|||<qW|j|j||jdk r(x,|jD]"}t|tr|j||j|<qWdS)NrQ)rXrHZ reset_indexrr!rgrr[rYshaperrrrftolistrrrlrr<r9rirT_encode_stringsrhrCr)rrtemprrrnew_typer4r4r5rMn s:             zStataWriter._prepare_pandasc Cs|j}t|dg}xt|jD]\}}||ks||kr8q|j|}|j}|jtjkrt|dd}|dkprt |dks|j }t d|d|j|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)rxrrzColumn `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)rlr9rrrTrrir=rrrrIrrrrrr_max_string_length) rra convert_strlrrrrTZinferred_dtypeencodedr4r4r5rk s"     zStataWriter._encode_stringscCsVt|j|j\|_|_}|dk r0|j|_t|_y|j|j|j d|j |j |j |j |j|j|j|j|j|j}|j||j|j|j|j Wntk rH}zj|j|jr4y"t|jttfrtj|jWn,tk r2t j!d|jdt"YnX|WYdd}~Xn X|jdS)N)rrz!This save was not successful but z/ could not be deleted. This file is not valid.)#r+rOrKrQrJrLr _write_headerrrI _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 Exception_closerrrosunlinkOSErrorrprqResourceWarning)rr'recordsexcr4r4r5 write_file sD    zStataWriter.write_filec Cs|jdk st|jdk rPt|jts(t|j}|jd|j|_|jj|jy|jjWnt k rrYnX|j r|jj dS)aA 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. In either case, attempt to flush the file contents to ensure they are written to disk (if supported) Nr) rQrrLrrrrrflushAttributeErrorrJr)rrr4r4r5r s   zStataWriter._closecCsdS)zNo-op, future compatibilityNr4)rr4r4r5rs szStataWriter._write_mapcCsdS)zNo-op, future compatibilityNr4)rr4r4r5r sz!StataWriter._write_file_close_tagcCsdS)zNo-op, future compatibilityNr4)rr4r4r5r{ sz"StataWriter._write_characteristicscCsdS)zNo-op, future compatibilityNr4)rr4r4r5r~ szStataWriter._write_strlscCs|jtdddS)z"Write 5 zeros for expansion fieldsrrN)rSr)rr4r4r5rz sz#StataWriter._write_expansion_fieldscCs&x |jD]}|j|j|jqWdS)N)rVrTrrN)rrr4r4r5r s zStataWriter._write_value_labels)rrr+c CsH|j}|jtjdd|j|dkr(dp*d|jd|jd|jtj|d|jdd|jtj|d |jdd |dkr|j|jtd d n|j|jt|dd d |dkrt j j }nt |t j st d ddddddddddddg }ddt |D}|jd||j|jd}|j|j|dS)Nrrrr0rrerrarrz"time_stamp should be datetime typeJanFebMarAprMayJunJulAugSepOctNovDeccSsi|]\}}||dqS)r*r4)r1rr<r4r4r5 Q sz-StataWriter._write_header..z%d z %Y %H:%M)rNrTrrrSrr_null_terminate_bytesrr0nowrrIrstrftimer<)rrrrmonths month_lookuptsr4r4r5rr" s<      zStataWriter._write_headercCs&x |jD]}|jtjd|qWdS)Nr)rrTrr)rrr4r4r5rtY s z!StataWriter._write_variable_typescCs:x4|jD]*}|j|}t|ddd}|j|qWdS)Nrr)r_null_terminate_strrrS)rrr4r4r5ru] s  zStataWriter._write_varnamescCs"tdd|jd}|j|dS)Nrrer*)rrrS)rrr4r4r5rve szStataWriter._write_sortlistcCs$x|jD]}|jt|dqWdS)Nr)rrSr)rrtr4r4r5rwj s zStataWriter._write_formatscCsdx^t|jD]P}|j|rL|j|}|j|}t|ddd}|j|q |jtddq WdS)Nrrr)rrrUrrrrS)rrrr4r4r5rxo s    z$StataWriter._write_value_label_namescCstdd}|jdkr6xt|jD]}|j|q WdSxp|jD]f}||jkr|j|}t|dkrjtdtdd|D}|std|jt|dq>|j|q>WdS)Nrrrz.Variable labels must be 80 characters or fewercss|]}t|dkVqdS)N)r)r1rr4r4r5r sz5StataWriter._write_variable_labels..zKVariable labels must contain only characters that can be encoded in Latin-1) rrrrrSrrrIr)rblankrrrZ is_latin1r4r4r5ry{ s       z"StataWriter._write_variable_labelscCs|S)zNo-op, future compatibilityr4)rrr4r4r5_convert_strls szStataWriter._convert_strlsc Cs |j}|j}|j}|jdk rRx4t|D](\}}||kr&t|||j|||<q&W|j|}i}|jtt j k}xt|D]\}}||}||j kr||j dj t|fd||<d|} | ||<||j| ||<qz||j} |s| j|j} | ||<qzW|jd|dS)Nr)argsrF)r/Z column_dtypes)rrrlrrrrrNr{r|rrorZrrrlrTrZ to_records) rrrrarrrZnative_byteorderrstyperTr4r4r5r| s.       zStataWriter._prepare_data)rr+cCs|j|jdS)N)rTtobytes)rrr4r4r5r} szStataWriter._write_data)rr+cCs |d7}|S)Nr0r4)rr4r4r5r szStataWriter._null_terminate_strcCs|j|j|jS)N)rrr)rrr4r4r5r sz!StataWriter._null_terminate_bytes)NTNNNNrF)NN)5rrrrrorrr!r r rrrr0rr rrSrrTrYr[r\rbrgr#rhrMrkrrrsrr{r~rzrrrrtrurvrwrxryrriZrecarrayr|r} staticmethodrrr!r4r4)rr5rECsVO\*E7%(3  rE)rTrr@r+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. rN)dfrfrrcCs|dkrtd||_||_||_ddi|_|dkr:tj}t||_d}d}d |_ |dkrjd }d}d |_ n|dkrxd }nd }ddd||_ ||_ ||_ dS)Nrrrz,Only dta versions 117, 118 and 119 supportedrrrr zutf-8razlatin-1rfrrer)rrr)rr) rIZ_dta_verrrf _gso_tabler|rr{rNr_o_offet _gso_o_type _gso_v_type)rrrfrrZ gso_v_typeZ gso_o_typeZo_sizer4r4r5r s,  zStataStrLWriter.__init__)rr+cCs|\}}||j|S)N)r)rrrrfr4r4r5 _convert_key4 szStataStrLWriter._convert_key)r+cs|j}|j}t|j||j}fdd|jD}tj|jtjd}xt|j D]|\}\}}xnt|D]b\} \} } || } | dkrdn| } |j | d} | dkr| d|df} | || <|j | ||| 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|]}|j|fqSr4)r/)r1r)rfr4r5r6Y sz2StataStrLWriter.generate_table..)rTNrr*) rrrrfriemptyrirrZiterrowsgetr)r gso_tableZgso_dfselectedZ col_indexrrfidxrowrrrrrrr4)rfr5generate_table8 s$   zStataStrLWriter.generate_table)rr+cCst}tdd}tj|jdd}tj|jdd}|j|j}|j|j}|jd}x|jD]\} } | d krrq`| \} } |j||jtj|| |jtj|| |j|t| d} |jtj|t | d|j| |j|q`W|j d|j 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. rasciirrrrzutf-8r*)rr) rrrrrNrrrcrrrr)rrrZgsoZgso_typenullZv_typeZo_typeZlen_typeZstrlZvorrfZ utf8_stringr4r4r5 generate_blobk s*         zStataStrLWriter.generate_blob)rN)rrrrr!r rrCr rrrr rrrr4r4r4r5r s &3rcseZdZdZdZdZd6eeee e e fe ee ee j ee ee e e feee ee ee e fdfd fdd Zeee efe ed d d Ze dd ddZd7ee ee j ddddZddddZddddZddddZddddZddddZddddZddd d!Zddd"d#Zddd$d%Zddd&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) .. versionadded:: 0.23.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 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() irNTrF) r&rrarGrrrrrpr'c sHg|_| dk r|jj| tj||||||||| d i|_d|_dS)N)rrrrr')rnextendrjr_map _strl_blob) rr&rrarGrrrrrpr')rr4r5r s zStataWriter117.__init__)rtagr+cCs<t|trt|d}td|dd|td|ddS)zSurround val with zutf-8rrzzutf-8releaserZMSFZLSFrrrrKrr NNrrrrz"time_stamp should be datetime typerrrrrrrrrrrrcSsi|]\}}||dqS)r*r4)r1rr<r4r4r5rb sz0StataWriter117._write_header..z%d z %Y %H:%M timestamprheader)rNrTrrrrr _dta_versionrrrrrrrr0rrrIrrr<rr)rrrrrrZ nobs_sizerZ encoded_labelZ label_sizeZ label_lenrrrZstata_tsr4r4r5rr3 sJ      zStataWriter117._write_header)r+cCs|jdk st|jsDtdd|jjfddddddddddddf|_|jj|jdt}x*|jjD]}|jt j |j d|qhW|jd|j |j |jddS)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. N stata_datarmapvariable_typesvarnamessortlistformatsvalue_label_namesrcharacteristicsrstrlsrstata_data_close end-of-filer )rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rr)rQrrrVrrrrJrrrrNrTrr)rrrr4r4r5rsn s.   zStataWriter117._write_mapcCs\|jdt}x&|jD]}|jtj|jd|qW|jd|j|j |j ddS)Nrrr) rrrrrrrNrrTrr)rrrr4r4r5rt s    z$StataWriter117._write_variable_typescCs|jdt}|jdkrdnd}x@|jD]6}|j|}t|ddj|j|d}|j|q*W|j d|j |j |j ddS)Nrrrrr*r) rrrrrrrrrrrTrr)rrZvn_lenrr4r4r5ru s    zStataWriter117._write_varnamescCs@|jd|jdkrdnd}|j|jd||jdddS)Nrrrerarr*)rrrTrr)rZ sort_sizer4r4r5rv s zStataWriter117._write_sortlistcCsn|jdt}|jdkrdnd}x&|jD]}|jt|j|j|q*W|jd|j |j |j ddS)Nrrrrr) rrrrrrrrrrTrr)rrZfmt_lenrtr4r4r5rw s   zStataWriter117._write_formatscCs|jdt}|jdkrdnd}x\t|jD]N}d}|j|rJ|j|}|j|}t|ddj |j |d}|j |q.W|j d|j |j|jddS)Nrrrrrr*r)rrrrrrUrrrrrrrrTrr)rrvl_lenrr encoded_namer4r4r5rx s     z'StataWriter117._write_value_label_namesc Cs@|jdt}|jdkrdnd}td|d}|jdkr|xt|jD]}|j|qFW|jd|j |j |j ddSx|j D]}||jkr|j|}t |dkrtdy|j|j}Wn4tk r}ztd |j|WYdd}~XnX|jt||dq|j|qW|jd|j |j |j ddS) Nrrri@rr*rz.Variable labels must be 80 characters or fewerzDVariable labels must contain only characters that can be encoded in )rrrrrrrrrrTrrrrrIrrUnicodeEncodeError) rrrrrrrrqrr4r4r5ry s2         z%StataWriter117._write_variable_labelscCs |jd|j|jdddS)Nrr)rrTr)rr4r4r5r{ s z%StataWriter117._write_characteristicscCs0|jd|jd|j|j|jddS)Nrss)rrTr)rrr4r4r5r} s  zStataWriter117._write_datacCs"|jd|j|j|jddS)Nr)rrTrr)rr4r4r5r~ s zStataWriter117._write_strlscCsdS)zNo-op in dta 117+Nr4)rr4r4r5rz sz&StataWriter117._write_expansion_fieldscCsf|jdt}x0|jD]&}|j|j}|j|d}|j|qW|jd|j|j|j ddS)NrZlblr) rrrVrrNrrrrTr)rrrZlabr4r4r5r s     z"StataWriter117._write_value_labelscCs(|jd|jtdd|jddS)Nrz zutf-8z end-of-file)rrTr)rr4r4r5r s z$StataWriter117._write_file_close_tagcCs<x6|jjD](\}}||jkr |jj|}||j|<q WdS)z Update column names for conversion to strl if they might have been changed to comply with Stata naming rules N)rPrcrnr/)rorignewrr4r4r5r\ s  z!StataWriter117._update_strl_names)rr+csJfddt|D}|rFt||jd}|j\}}|}|j|_|S)zg Convert columns to StrLs if either very large or in the convert_strl variable cs,g|]$\}}j|dks$|jkr|qS)i)rrn)r1rr)rr4r5r6 sz1StataWriter117._convert_strls..)r)rrrrrr)rrZ convert_colsZsswtabZnew_datar4)rr5r s    zStataWriter117._convert_strls)rr+cCsng|_g|_x\|jD]P\}}||jk}t||j||j|d}|jj||jjt||j||qWdS)N)r?r@) rrrcrnrDrrrr)rrrrTr@rtr4r4r5rh" s  z%StataWriter117._set_formats_and_types)NTNNNNNrF)NN))rrrrrorrr!r r rrrr0r rr rrrrrrrrsrtrurvrwrxryr{r}r~rzrrr\rr#rhr!r4r4)rr5r sBVf7"  "  rcseZdZdZdZd eeeee e fe ee ee j ee eee e fee e eeee ee e fdfd 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-8NTrF) r&rrarGrrrrrprr'c sz| dkr |jddkrdnd} n0| dkr2tdn| dkrP|jddkrPtdtj||||||||| | d | |_dS) Nr*irrz"version must be either 118 or 119.zKYou must use version 119 for data sets containing more than32,767 variables)rarGrrrrrpr')rr)rirIrjrr) rr&rrarGrrrrrprr')rr4r5r s& zStataWriterUTF8.__init__)rr+cCs~xx|D]p}t|dkrN|dks&|dkrN|dks6|dkrN|dksF|dkrN|dksjdt|kodd knr|j|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 _. rr]r^rr_rr`rr)rra)rrrr4r4r5rb s  z'StataWriterUTF8._validate_variable_name) NTNNNNNNrF)rrrrrrr!r r rrrr0r rCrr rrbr!r4r4)rr5r3 sblr) TTNFTNTNF)rF)nr collectionsrr0iorrrpathlibrrr|typingrrrr r r r r rrrpZdateutil.relativedeltarZnumpyriZpandas._libs.librZpandas._libs.writersrZpandas._typingrrZpandas.util._decoratorsrZpandas.core.dtypes.commonrrrZpandasrrrrrrrr Zpandas.core.framer!Zpandas.core.indexes.baser"Zpandas.core.seriesr#Zpandas.io.commonr$r%r&r'r(rZ_statafile_processing_params1Z_statafile_processing_params2Z_chunksize_paramsZ_iterator_paramsZ _reader_notesZ_read_stata_docr rrrorvrrrBWarningrrrrrrdrrrrrrIteratorr_rrCr%r+r{rrTr9r<r>rDrErrrrrrr4r4r4r5 s  0     (     ,$#k  Yn%r&,'  %+* 7