B []&@sdZddlmZddlZddlZddlmZddlZddlZddl m Z ddl m Z m Z mZddlZddlZddlmmZddlmmZddlmmZddlmZddlmZmZmZm Z dd l!m"Z"dd l#m$Z$dd l%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3dd l4m5Z5dd l6m7Z7ddl8m9Z9ddl:m;Z;ddlm?Z?ddl@mAZAmBZBmCZCmDZDddlEmFZFddlGmHZIddlJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSddlTmUZUdZVde dWeXeKddddZYdqddZZd d!Z[e9d"d#d$Z\ddd%ej]d&d'dd(dddddddd&ddddd&ddd)d'd'd'dddd'dd'dd&d'd&d*%Z^d'd&d&d'd&d&dd+Z_d(d,dd-Z`d.hZad/d0hZbiZcedZedrd2d3Zfefd4d1d5Zge"eYjhd4d6d7d8egZgefd9d:d5Zie"eYjhd9d;dZjGd?d@d@eLZkdAdBZldCdDZmdEdFZndGdHZodIdJZpdKdLZqdMdNZrGdOdPdPZsGdQdRdResZtdSdTZudUdVZvGdWdXdXesZwdtdYdZZxdud[d\Zyd]d^Zzdvd_d`Z{dadbZ|dwdcddZ}dedfZ~dgdhZdidjZdkdlZGdmdndneLZGdodpdpewZdS)xzM Module contains tools for processing files into DataFrames or other objects ) defaultdictN)StringIO)fill)AnyDictSet)parsing)AbstractMethodErrorEmptyDataError ParserError ParserWarning)Appender)astype_nansafe) ensure_object ensure_str is_bool_dtypeis_categorical_dtypeis_dtype_equalis_extension_array_dtypeis_float is_integeris_integer_dtype is_list_likeis_object_dtype is_scalaris_string_dtype pandas_dtype)CategoricalDtype)isna)FilePathOrBuffer) algorithms) Categorical) DataFrame)Index MultiIndex RangeIndexensure_index_from_sequences)Series) datetimes) _NA_VALUES BaseIterator UnicodeReader UTF8Recoder _get_handle_infer_compression_validate_header_argget_filepath_or_buffer is_file_like)generic_parserua {summary} Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for `IO Tools `_. 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.csv. 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``. sep : str, default {_default_sep} Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detect the separator by Python's builtin sniffer tool, ``csv.Sniffer``. In addition, separators longer than 1 character and different from ``'\s+'`` will be interpreted as regular expressions and will also force the use of the Python parsing engine. Note that regex delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``. delimiter : str, default ``None`` Alias for sep. header : int, list of int, default 'infer' Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to ``header=0`` and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to ``header=None``. Explicitly pass ``header=0`` to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if ``skip_blank_lines=True``, so ``header=0`` denotes the first line of data rather than the first line of the file. names : array-like, optional List of column names to use. If file contains no header row, then you should explicitly pass ``header=None``. Duplicates in this list are not allowed. index_col : int, str, sequence of int / str, or False, default ``None`` Column(s) to use as the row labels of the ``DataFrame``, either given as string name or column index. If a sequence of int / str is given, a MultiIndex is used. Note: ``index_col=False`` can be used to force pandas to *not* use the first column as the index, e.g. when you have a malformed file with delimiters at the end of each line. usecols : list-like or callable, optional Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in `names` or inferred from the document header row(s). For example, a valid list-like `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a DataFrame from ``data`` with element order preserved use ``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns in ``['foo', 'bar']`` order or ``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for ``['bar', 'foo']`` order. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. squeeze : bool, default False If the parsed data only contains one column then return a Series. prefix : str, optional Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ... mangle_dupe_cols : bool, default True Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than 'X'...'X'. Passing in False will cause data to be overwritten if there are duplicate names in the columns. dtype : Type name or dict of column -> type, optional Data type for data or columns. E.g. {{'a': np.float64, 'b': np.int32, 'c': 'Int64'}} Use `str` or `object` together with suitable `na_values` settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion. engine : {{'c', 'python'}}, optional Parser engine to use. The C engine is faster while the python engine is currently more feature-complete. converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels. true_values : list, optional Values to consider as True. false_values : list, optional Values to consider as False. skipinitialspace : bool, default False Skip spaces after delimiter. skiprows : list-like, int or callable, optional Line numbers to skip (0-indexed) or number of lines to skip (int) at the start of the file. If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be ``lambda x: x in [0, 2]``. skipfooter : int, default 0 Number of lines at bottom of file to skip (Unsupported with engine='c'). nrows : int, optional Number of rows of file to read. Useful for reading pieces of large files. na_values : scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: 'z', 'Fz )subsequent_indenta"'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether `na_values` is passed in, the behavior is as follows: * If `keep_default_na` is True, and `na_values` are specified, `na_values` is appended to the default NaN values used for parsing. * If `keep_default_na` is True, and `na_values` are not specified, only the default NaN values are used for parsing. * If `keep_default_na` is False, and `na_values` are specified, only the NaN values specified `na_values` are used for parsing. * If `keep_default_na` is False, and `na_values` are not specified, no strings will be parsed as NaN. Note that if `na_filter` is passed in as False, the `keep_default_na` and `na_values` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. skip_blank_lines : bool, default True If True, skip over blank lines rather than interpreting as NaN values. parse_dates : bool or list of int or names or list of lists or dict, default False The behavior is as follows: * boolean. If True -> try parsing the index. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * dict, e.g. {{'foo' : [1, 3]}} -> parse columns 1, 3 as date and call result 'foo' If a column or index cannot be represented as an array of datetimes, say because of an unparseable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``. To parse an index or column with a mixture of timezones, specify ``date_parser`` to be a partially-applied :func:`pandas.to_datetime` with ``utc=True``. See :ref:`io.csv.mixed_timezones` for more. Note: A fast-path exists for iso8601-formatted dates. infer_datetime_format : bool, default False If True and `parse_dates` is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x. keep_date_col : bool, default False If True and `parse_dates` specifies combining multiple columns then keep the original columns. date_parser : function, optional Function to use for converting a sequence of string columns to an array of datetime instances. The default uses ``dateutil.parser.parser`` to do the conversion. Pandas will try to call `date_parser` in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the string values from the columns defined by `parse_dates` into a single array and pass that; and 3) call `date_parser` once for each row using one or more strings (corresponding to the columns defined by `parse_dates`) as arguments. dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : boolean, default True If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. .. versionadded:: 0.25.0 iterator : bool, default False Return TextFileReader object for iteration or getting chunks with ``get_chunk()``. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs `_ for more information on ``iterator`` and ``chunksize``. compression : {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no decompression). If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. .. versionadded:: 0.18.1 support for 'zip' and 'xz' compression. thousands : str, optional Thousands separator. decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). lineterminator : str (length 1), optional Character to break file into lines. Only valid with C parser. quotechar : str (length 1), optional The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored. quoting : int or csv.QUOTE_* instance, default 0 Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3). doublequote : bool, default ``True`` When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional One-character string used to escape other characters. comment : str, optional Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter `header` but not by `skiprows`. For example, if ``comment='#'``, parsing ``#empty\na,b,c\n1,2,3`` with ``header=0`` will result in 'a,b,c' being treated as the header. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python standard encodings `_ . dialect : str or csv.Dialect, optional If provided, this parameter will override values (default or not) for the following parameters: `delimiter`, `doublequote`, `escapechar`, `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details. error_bad_lines : bool, default True Lines with too many fields (e.g. a csv line with too many commas) will by default cause an exception to be raised, and no DataFrame will be returned. If False, then these "bad lines" will dropped from the DataFrame that is returned. warn_bad_lines : bool, default True If error_bad_lines is False, and warn_bad_lines is True, a warning for each "bad line" will be output. delim_whitespace : bool, default False Specifies whether or not whitespace (e.g. ``' '`` or ``' '``) will be used as the sep. Equivalent to setting ``sep='\s+'``. If this option is set to True, nothing should be passed in for the ``delimiter`` parameter. .. versionadded:: 0.18.1 support for the Python parser. low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the `dtype` parameter. Note that the entire file is read into a single DataFrame regardless, use the `chunksize` or `iterator` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for `filepath_or_buffer`, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are `None` for the ordinary converter, `high` for the high-precision converter, and `round_trip` for the round-trip converter. Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.{func_name}('data.csv') # doctest: +SKIP cCsXdj||d}|dk rTt|r={min_val:d})namemin_valN)formatrint ValueErrorr)r5valr6msgr<5/tmp/pip-install-svzetoqp/pandas/pandas/io/parsers.py_validate_integerss   r>cCs(|dk r$t|tt|kr$td|S)am Check if the `names` parameter contains duplicates. If duplicates are found, we issue a warning before returning. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. Returns ------- names : array-like or None The original `names` parameter. Nz Duplicate names are not allowed.)lensetr9)namesr<r<r=_validate_namessrB)filepath_or_bufferc Cs"|dd}|dk r.tdd|}||d<|dd}t||}t|||\}}}}||d<|dddk rt|dtrd |d<|d d }td |d dd }|dd} t |ddt |f|} |s|r| Sz| | } Wd| X|ry | Wnt k rYnX| S)zGeneric reader of line files.encodingN_- compressioninfer date_parser parse_datesTiteratorF chunksizenrowsrA)getresublowerr.r0 isinstanceboolr>rBTextFileReaderreadcloser9) rCkwdsrDrGZ fp_or_bufrEZ should_closerKrLrNparserdatar<r<r=_reads8        r["TFrH.)% delimiter escapechar quotecharquoting doublequoteskipinitialspacelineterminatorheader index_colrAprefixskiprows skipfooterrN na_valueskeep_default_na true_values false_values convertersdtype cache_dates thousandscommentdecimalrJ keep_date_coldayfirstrIusecolsrLverboserDsqueezerGmangle_dupe_colsinfer_datetime_formatskip_blank_lines)delim_whitespace na_filter low_memory memory_maperror_bad_lineswarn_bad_linesfloat_precisiond)colspecs infer_nrowswidthsrir~r,c0sdddddddddddddddddddddddddddddddddddtjddddddddtdddf0tdfd d }||_|S) NrHFTrr]r\r~)rCc142s|*dk r$|dko|k}1t|1d}2nt}2|dkr6|}|-rJ|krJtd| dk rXd}3nd} d}3|2j|| |*| |3|&|'|$|%||#|||||||| |||!|(|"||||||||| | |||)||/|0||-|,|+|.| ||d0t||2S)N) sep_overridezXSpecified a delimiter with both sep and delim_whitespace=True; you can only specify one.TcF)0r^enginedialectrGengine_specifiedrbr_r`rarcrdrerfrArgrhrirjrlrmrkrqrrrsrJrtrurIrprNrKrLrnrorvrwrDrxrrr}r|rrr~ryrzr{)dictr9updater[)4rCsepr^rerArfrvrxrgryrorrnrlrmrcrhrirNrjrkr}rwr{rJrzrtrIrurprKrLrGrqrsrdr`rarbr_rrrDrrrr|r~rrrrXr) default_sepr<r=parser_fs~H  z'_make_parser_function..parser_f)csv QUOTE_MINIMAL_c_parser_defaultsr__name__)r5rrr<)rr=_make_parser_functionsd[rread_csv)rz8Read a comma-separated values (csv) file into DataFrame.z',') func_namesummaryZ _default_sep read_table z+Read general delimited file into DataFrame.z'\\t' (tab-stop)cKs|dkr|dkrtdn|dkr2|dk r2td|dk rlgd}}x&|D]}||||f||7}qJW||d<||d<d|d <t||S) aM Read a table of fixed-width formatted lines into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the `online docs for IO Tools `_. 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.csv``. 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``. colspecs : list of tuple (int, int) or 'infer'. optional A list of tuples giving the extents of the fixed-width fields of each line as half-open intervals (i.e., [from, to[ ). String value 'infer' can be used to instruct the parser to try detecting the column specifications from the first 100 rows of the data which are not being skipped via skiprows (default='infer'). widths : list of int, optional A list of field widths which can be used instead of 'colspecs' if the intervals are contiguous. infer_nrows : int, default 100 The number of rows to consider when letting the parser determine the `colspecs`. .. versionadded:: 0.24.0 **kwds : optional Optional keyword arguments can be passed to ``TextFileReader``. Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. Examples -------- >>> pd.read_fwf('data.csv') # doctest: +SKIP Nz&Must specify either colspecs or widths)NrHz4You must specify only one of 'widths' and 'colspecs'rrrz python-fwfr)r9appendr[)rCrrrrXcolwr<r<r=read_fwfsA    rc@speZdZdZdddZddZddZd d Zd d Zd dZ dddZ ddZ dddZ ddZ dddZdS)rUzF Passed dialect overrides any of the related parser options Nc Ks||_|dk rd}nd}d}|d||_|ddk r|d}|tkrXt|}xdD]}yt||}Wn(tk rtdj |ddYnXt |}|||} g} | |kr| |krd j || |d } |d kr| d ds| | | r t jd | tdd|||<q^W|drX|ds<|drDtd|drXtd|dddkr|ddkr~dnd|d<||_||_d|_d|_||} | dd|_| dd|_| dd|_||||_|| |\|_|_d|kr |d|jd<||jdS)NTpythonFrr)r^rbr_rcr`raz$Invalid dialect '{dialect}' provided)rzConflicting values for '{param}': '{val}' was provided, but the dialect specifies '{diaval}'. Using the dialect-specified value.)paramr:Zdiavalr^rz ) stacklevelrirKrLz*'skipfooter' not supported for 'iteration'rNz''skipfooter' not supported with 'nrows'rerHrArrxhas_index_names)frO_engine_specifiedr list_dialects get_dialectgetattrAttributeErrorr9r7_parser_defaultspoprwarningswarnjoinr orig_optionsr_engine_currow_get_options_with_defaultsrLrNrx_check_file_or_buffer_clean_optionsoptions _make_engine) selfrrrXrrrZ dialect_valparser_defaultprovidedZ conflict_msgsr;rr<r<r=__init__!sd          zTextFileReader.__init__cCs|jdS)N)rrW)rr<r<r=rWszTextFileReader.closecCs|j}i}x>tD]2\}}|||}|dkr>|s>tdq|||<qWx~tD]r\}}||kr||}|dkr||krd|kr|tkrq|t||krqtd||fn t||}|||<qTW|dkrx$tD]\}}|||||<qW|S)Nryz3Setting mangle_dupe_cols=False is not supported yetrrz1The %r option is not supported with the %r enginez python-fwf) rritemsrOr9r_python_unsupported_deprecated_defaults _fwf_defaults)rrrXrargnamedefaultvaluer<r<r=rs2     z)TextFileReader._get_options_with_defaultscCs.t|r*d}|dkr*t||s*d}t||S)N__next__rz|ddkr>d}d}tpHd}|dkrh|sh|dkrfd }d}n|dk rt|d kr|dkr|d krd |d<|d=n|d krd}d}nz|rd|krd |d<nd|dk r(d } yt||d krd} Wntk rd} YnX| s(|d kr(dj|d}d}|d} | dk rxt| t t frxt| d krxt | dkrx|d krxd}d}|r|rt ||dkrxt D] } || =qWd|krxBtD]:} |r|| t| krdj|| d} t | || =qW|rtjd|tdd|d} |d}|d}|d}|d}t|dd }xRtD]J} t| }t| }d!j| d"} || ||kr|| d#7}n||| <qTW|d krtj|td$d| d krt d%t| rt| tttjfs| g} | |d<|dk r t|n|}|dk r 1 char and different from '\s+' are interpreted as regex)Fzithe separator encoded in {encoding} is > 1 char long, and the 'c' engine does not support such separators)rDr`zxord(quotechar) > 127, meaning the quotechar is larger than one byte, and the 'c' engine does not support such quotecharszFalling back to the 'python' engine because {reason}, but this causes {option!r} to be ignored as it is not supported by the 'python' engine.)reasonoptionzjFalling back to the 'python' engine because {0}; you can avoid this warning by specifying engine='python'.)rrfrArnrjrhrezQThe '{arg}' argument has been deprecated and will be removed in a future version.)argz rz)The value of index_col couldn't be 'True'z=Type converters must be a dict or subclass, input was a {0!r}rk na_fvalues)&copyrsysgetfilesystemencodingr?encodeUnicodeDecodeErrorr7rSstrbytesordr9_c_unsupportedrrrrr r/_deprecated_argsrrO FutureWarning _is_index_collisttuplenpndarrayr TypeErrortyper_clean_na_valuesrranger@callable)rrrresultrZfallback_reasonrr|rDZ encodeabler`rr;rfrArnrjrhZ depr_warningrZ depr_defaultrkrr<r<r=rs                           zTextFileReader._clean_optionscCs,y|Stk r&|YnXdS)N) get_chunk StopIterationrW)rr<r<r=rfs zTextFileReader.__next__rcCs^|dkrt|jf|j|_n>|dkr*t}n|dkr8t}ntdj|d||jf|j|_dS)Nrrz python-fwfzKUnknown engine: {engine} (valid options are "c", "python", or "python-fwf"))r)CParserWrapperrrr PythonParserFixedWidthFieldParserr9r7)rrklassr<r<r=rms zTextFileReader._make_enginecCs t|dS)N)r )rr<r<r=_failover_to_python}sz"TextFileReader._failover_to_pythoncCstd|}|j|}||\}}}|dkr`|rZttt|}t|j |j |}qhd}nt|}t |||d}|j |7_ |j rt|j dkr||j d S|S)NrNr)columnsindexrM)r>rrV _create_indexr?nextitervaluesr%rr"rxrr)rrNretrrcol_dictnew_rowsZdfr<r<r=rVs  zTextFileReader.readcCs|\}}}|||fS)Nr<)rrrrrr<r<r=rs zTextFileReader._create_indexcCsF|dkr|j}|jdk r:|j|jkr(tt||j|j}|j|dS)N)rN)rLrNrrminrV)rsizer<r<r=rs  zTextFileReader.get_chunk)N)r)N)N)r __module__ __qualname____doc__rrWrrrrrrrVrrr<r<r<r=rUs `(+  rUcCs|dk o|dk S)NFr<)rr<r<r=rsrcCs&t|o$t|t o$tdd|DS)a5 Check whether or not the `columns` parameter could be converted into a MultiIndex. Parameters ---------- columns : array-like Object which may or may not be convertible into a MultiIndex Returns ------- boolean : Whether or not columns could become a MultiIndex css|]}t|tVqdS)N)rSr).0rr<r<r= sz,_is_potential_multi_index..)r?rSr$all)rr<r<r=_is_potential_multi_indexs rcs"trfddt|DSS)z Check whether or not the 'usecols' parameter is a callable. If so, enumerates the 'names' parameter and returns a set of indices for each entry in 'names' that evaluates to True. If not a callable, returns 'usecols'. csh|]\}}|r|qSr<r<)rir5)rvr<r= sz$_evaluate_usecols..)r enumerate)rvrAr<)rvr=_evaluate_usecolssrcs2fdd|D}t|dkr.tdj|d|S)a% Validates that all usecols are present in a given list of names. If not, raise a ValueError that shows what usecols are missing. Parameters ---------- usecols : iterable of usecols The columns to validate are present in names. names : iterable of names The column names to check against. Returns ------- usecols : iterable of usecols The `usecols` parameter if the validation succeeds. Raises ------ ValueError : Columns were missing. Error message will list them. csg|]}|kr|qSr<r<)rr)rAr<r= sz+_validate_usecols_names..rzGUsecols do not match columns, columns expected but not found: {missing})missing)r?r9r7)rvrArr<)rAr=_validate_usecols_namess   rcCs$t|std|dkr td|S)a Validate the 'skipfooter' parameter. Checks whether 'skipfooter' is a non-negative integer. Raises a ValueError if that is not the case. Parameters ---------- skipfooter : non-negative integer The number of rows to skip at the end of the file. Returns ------- validated_skipfooter : non-negative integer The original input if the validation succeeds. Raises ------ ValueError : 'skipfooter' was not a non-negative integer. zskipfooter must be an integerrzskipfooter cannot be negative)rr9)rir<r<r=_validate_skipfooter_args rcCsbd}|dk rZt|r|dfSt|s,t|tj|dd}|dkrJt|t|}||fS|dfS)a+ Validate the 'usecols' parameter. Checks whether or not the 'usecols' parameter contains all integers (column selection by index), strings (column by name) or is a callable. Raises a ValueError if that is not the case. Parameters ---------- usecols : list-like, callable, or None List of columns to use when parsing or a callable that can be used to filter a list of table columns. Returns ------- usecols_tuple : tuple A tuple of (verified_usecols, usecols_dtype). 'verified_usecols' is either a set if an array-like is passed in or 'usecols' if a callable or None is passed in. 'usecols_dtype` is the inferred dtype of 'usecols' if an array-like is passed in or None if a callable or None is passed in. z['usecols' must either be list-like of all strings, all unicode, all integers or a callable.NF)skipna)emptyintegerstringunicode)rrr9libZ infer_dtyper@)rvr; usecols_dtyper<r<r=_validate_usecols_arg sr cCsBd}|dk r>t|r(t|s>t|nt|ttfs>t||S)z Check whether or not the 'parse_dates' parameter is a non-boolean scalar. Raises a ValueError if that is the case. zSOnly booleans, lists, and dictionaries are accepted for the 'parse_dates' parameterN)rrZis_boolrrSrr)rJr;r<r<r=_validate_parse_dates_arg>s  r c@seZdZddZddZeddZddZd"d d Zd d Z d#ddZ d$ddZ d Z ddZ ddZd%ddZd&ddZd'ddZddZd d!ZdS)( ParserBasecCs6|d|_d|_|dd|_|dd|_t|_d|_d|_ t |dd|_ |dd|_ |dd|_ |dd|_|d |_|d |_|d d|_|d d |_|d|_|d|_|dd |_|dd|_|dd |_t|j |j |j|jd|_|d|_t|jtttjfrt t!t"|jsJt#dt$dd|jDrht#d|dr|t#d|drt#d|jdk r t|jtttjf}|rt t!t"|js t"|js t#dnB|jdk rt"|jst#dn |jdk r |jdkr t#dd|_%d |_&g|_'dS)NrArgrfrJFrIrurtrjrr}rkTrlrmryrzrp)rIrurzrprez*header must be integer or list of integerscss|]}|dkVqdS)rNr<)rrr<r<r=r|sz&ParserBase.__init__..z8cannot specify multi-index header with negative integersrvz;cannot specify usecols when specifying a multi-index headerz9cannot specify names when specifying a multi-index headerzLindex_col must only contain row numbers when specifying a multi-index headerrzUPassing negative integer to header is invalid. For no header, use header=None instead)(rOrA orig_namesrrgrfr@ unnamed_cols index_names col_namesr rJrIrurtrjrr}rkrlrmryrzrp_make_date_converter _date_convrerSrrrrrmaprr9any_name_processed _first_chunkhandles)rrXZ is_sequencer<r<r=rVsj            zParserBase.__init__cCsx|jD] }|qWdS)N)rrW)rrr<r<r=rWs zParserBase.closecCs6t|jtp4t|jto4t|jdko4t|jdtS)Nr)rSrJrrr?)rr<r<r=_has_complex_date_cols  z ParserBase._has_complex_date_colcCs|t|jtr|jS|jdk r(|j|}nd}|j|}t|jr\||jkpZ|dk oZ||jkS||jkpv|dk ov||jkSdS)N)rSrJrTrrfr)rrr5jr<r<r=_should_parse_datess       zParserBase._should_parse_datesFc s:t|dkr|d|||fSj}|dkr.g}t|tttjfsF|g}t||d}t |jj \}}}t|dfddtt fdd|D}||}xRt t|dD]>t fd d|Drtd jd d djDd qWt|rfdd|D}ndgt|}d}||||fS)zv extract and return the names, index_names, col_names header is a list-of-lists returned from the parsers rrNcstfddtDS)Nc3s|]}|kr|VqdS)Nr<)rr)rsicr<r=rszMParserBase._extract_multi_indexer_columns..extract..)rr)r) field_countr)rr=extractsz:ParserBase._extract_multi_indexer_columns..extractc3s|]}|VqdS)Nr<)rr)rr<r=rsz.c3s |]}t|jkVqdS)N)rr)rr)nrr<r=rszJPassed header=[{header}] are too many rows for this multi_index of columnsrcss|]}t|VqdS)N)r)rxr<r<r=rs)recs2g|]*}t|dr*|djkr*|dndqS)rN)r?r)rr)rr<r=rsz=ParserBase._extract_multi_indexer_columns..T)r?rfrSrrrrr@r_clean_index_namesrziprrr r7rre) rrerr passed_namesicrArfrr<)rrr rrr=_extract_multi_indexer_columnss4       z)ParserBase._extract_multi_indexer_columnscCs|jrt|}tt}t|}xt|D]z\}}||}xT|dkr|d||<|rt|dddj|d|df}ndj||d}||}q:W|||<|d||<q(W|S)NrrMrz{column}.{count})columncount)ryrrr8rrr7)rrAcountsZis_potential_mirr cur_countr<r<r=_maybe_dedup_namess     zParserBase._maybe_dedup_namesNcCst|rtj||d}|S)N)rA)rr$ from_tuples)rrrr<r<r=_maybe_make_multi_index_columns sz*ParserBase._maybe_make_multi_index_columnscCst|jr|jsd}nh|js4|||}||}nJ|jr~|jsdtt||j|j\|_ }|_d|_| ||}|j|dd}|rt |t |}| |d|}| ||j}||fS)NTF)try_parse_dates)rrfr_get_simple_index _agg_indexrr"rrr_get_complex_date_indexr?Z set_namesr-r)rrZalldatar indexnamerowrrEZcoffsetr<r<r= _make_index&s"   zParserBase._make_indexcCstdd}g}g}x.|jD]$}||}|||||qWx.tt|D]}|||jsN||qNW|S)NcSs"t|ts|Stdj|ddS)NzIndex {col} invalid)r)rSrr9r7)rr<r<r=ixCs z(ParserBase._get_simple_index..ix)rfrreversedsortedr_implicit_index)rrZrr5 to_removeridxrr<r<r=r/Bs   zParserBase._get_simple_indexc srfdd}g}g}x.|jD]$}||}|||||qWx(tt|D]}|||qRW|S)NcsLt|tr|Sdkr&tdj|dx tD]\}}||kr0|Sq0WdS)Nz1Must supply column order to use {icol!s} as index)icol)rSrr9r7r)r;rr)rr<r= _get_nameYs  z5ParserBase._get_complex_date_index.._get_name)rfrr6r7rremove) rrZrr<r9rr:r5rr<)rr=r1Xs    z"ParserBase._get_complex_date_indexTc Csg}xt|D]\}}|r.||r.||}|jrB|j}|j}n t}t}t|jtr|j |}|dk rt ||j|j|j \}}| |||B\}} | |qW|j } t|| }|S)N)rrrr}rjrr@rSrr_get_na_valuesrk _infer_typesrr&) rrr.arraysrZarr col_na_valuescol_na_fvaluescol_namerErAr<r<r=r0ws&    zParserBase._agg_indexc Csi}x|D]\}} |dkr&dn ||d} t|trJ||d} n|} |jrjt||||j\} } ntt} } | dk r | dk rtj d |t ddyt | | } Wn:tk rt| t|tj}t | | |} YnX|j| t| | Bdd\}}nt| pt| }| o$| }|| t| | B|\}}| rt|| r^t| ry2t| rt| s|dkrtdj |dWnttfk rYnX||| |}|||<|r|rtd j ||d qW|S) NzZBoth a converter and dtype were specified for column {0} - only the converter will be used)rF) try_num_boolrz,Bool column has NA values in column {column})r'z(Filled {count} NA values in column {c!s})r(r) rrOrSrr}r>rkr@rrr7r rZ map_inferr9r isinrviewrZuint8Zmap_infer_maskr?rrrrrrr _cast_typesprint)rdctrjrrwrnZdtypesrrrZconv_f cast_typerArBmaskZcvalsna_countZis_str_or_ea_dtyperEr<r<r=_convert_to_ndarrayssb        zParserBase._convert_to_ndarrayscCsd}t|jjtjtjfrft|t|}| }|dkr^t |rN| tj }t ||tj||fS|ryt||d}t| }Wqtk r|}|jtjkrt||d}YqXn|}|jtjkrt||d}|jtjkr |r tjt||j|jd}||fS)aU Infer types of values, possibly casting Parameters ---------- values : ndarray na_values : set try_num_bool : bool, default try try to cast values to numeric (first preference) or boolean Returns ------- converted : ndarray na_count : int rF)rlrm) issubclassrorrnumberZbool_r rFrsumrZastypeZfloat64ZputmasknanrZmaybe_convert_numericr ExceptionZobject_parsersZsanitize_objectslibopsZmaybe_convert_boolZasarrayrlrm)rrrjrErMrLrr<r<r=r?s4    zParserBase._infer_typescCst|r^t|to|jdk }t|s2|s2t|t}t| }t j || |||j d}nt|rt|}|}y|j||dStk rtdj|dYqXn.rcs$g|]\}}|ks|kr|qSr<r<)rrr )rvr<r=rsT)*rXrr rrOrSropenrrr,rfr rvr rTZ TextReader_readerrrArer?r&rrrrgrZ table_widthr rr@issubsetrr_set_noconvert_columnsr leading_colsrrr"r8)rsrcrXr$rr<)rrvr=rhsb         $        zCParserWrapper.__init__cCs@x|jD] }|qWy|jWntk r:YnXdS)N)rrWr^r9)rrr<r<r=rWs   zCParserWrapper.closecs<jjdkr$tjn(tjs8jdkrHjddndfdd}tjtrxΈjD].}t|trx|D] }||qWqp||qpWntjt rxj D].}t|trx|D] }||qWq||qWnHjr8tj tr"x0j D]}||qWnj dk r8|j dS)z Set the columns that should not undergo dtype conversions. Currently, any column that is involved with date parsing will not undergo such conversions. r)rNNcs:dk rt|r|}t|s*|}j|dS)N)rrr^Z set_noconvert)r!)rArrvr<r=_sets  z3CParserWrapper._set_noconvert_columns.._set) r r rrvsortrrArSrJrrrf)rrcr:kr<)rArrvr=r`s4            z%CParserWrapper._set_noconvert_columnscCs|jt|dS)N)r^set_error_bad_linesr8)rstatusr<r<r=rfsz"CParserWrapper.set_error_bad_linesNc sy|j|}Wntk r|jrd|_||j}t||j|j|j dd\}}| |j |j dk r||ttfdd|}||fSYnXd|_|j}|jjr|jrtdg}xTt|jjD]D}|jdkr||}n||j|}|j||dd}||qWt|}|j dk rD||}||}t|}d d t||D}|||\}}nzt|}t|j}||}|j dk r||}d d |D} d d t||D}|||\}}||| |\}}| ||j }|||fS)NFro)rocs |dkS)Nrr<)item)rr<r=z%CParserWrapper.read..z file structure not yet supportedT)r.cSsi|]\}\}}||qSr<r<)rrervr<r<r= Bsz'CParserWrapper.read..cSsg|] }|dqS)rMr<)rr!r<r<r=rRsz'CParserWrapper.read..cSsi|]\}\}}||qSr<r<)rrerrkr<r<r=rlTs) r^rVrrr+r _get_empty_metarfrrXrOr-rrv_filter_usecolsrfilterrrArarrXrr_maybe_parse_datesrr&r7r#rZrr4) rrNrZrArrr@rrr2r<)rr=rV s`                zCParserWrapper.readcs>t|j|dk r:t|tkr:fddt|D}|S)Ncs$g|]\}}|ks|kr|qSr<r<)rrr5)rvr<r=rcsz2CParserWrapper._filter_usecols..)rrvr?r)rrAr<)rvr=rn^s zCParserWrapper._filter_usecolscCsJt|jjd}d}|jjdkrB|jdk rBt||j|j\}}|_||fS)Nr)rr^rerarfr"r)rrAZ idx_namesr<r<r=_get_index_namesgs zCParserWrapper._get_index_namesTcCs|r||r||}|S)N)rr)rrrr.r<r<r=rprs z!CParserWrapper._maybe_parse_dates)N)T) rrrrrrWr`rfrVrnrqrpr<r<r<r=rcs_ 5 U  rcOsd|d<t||S)a6 Converts lists of lists/tuples into DataFrames with proper type inference and optional (e.g. string to datetime) conversion. Also enables iterating lazily over chunks of large files Parameters ---------- data : file-like object or list delimiter : separator character to use dialect : str or csv.Dialect instance, optional Ignored if delimiter is longer than 1 character names : sequence, default header : int, default 0 Row to use to parse column labels. Defaults to the first row. Prior rows will be discarded index_col : int or list, optional Column or columns to use as the (possibly hierarchical) index has_index_names: bool, default False True if the cols defined in index_col have an index name and are not in the header. na_values : scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. keep_default_na : bool, default True thousands : str, optional Thousands separator comment : str, optional Comment out remainder of line parse_dates : bool, default False keep_date_col : bool, default False date_parser : function, optional skiprows : list of integers Row numbers to skip skipfooter : int Number of line at bottom of file to skip converters : dict, optional Dict of functions for converting values in certain columns. Keys can either be integers or column labels, values are functions that take one input argument, the cell (not column) content, and return the transformed content. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8') squeeze : bool, default False returns Series if only one column. infer_datetime_format: bool, default False If True and `parse_dates` is True for a column, try to infer the datetime format based on the first datetime string. If the format can be inferred, there often will be a large parsing speed-up. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are None for the ordinary converter, 'high' for the high-precision converter, and 'round_trip' for the round-trip converter. rr)rU)argsrXr<r<r= TextParserxs6rscCstdd|DS)Ncss"|]}|dks|dkrdVqdS)rNrMr<)rrkr<r<r=rsz#count_empty_vals..)rQ)valsr<r<r=count_empty_valssruc@seZdZddZddZddZd3dd Zd d Zd4d d ZddZ ddZ ddZ ddZ ddZ ddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,Zd-d.Zd/d0Zd5d1d2ZdS)6rc st|d_g_d_d_|d_|d_|d_|d_ t j r`j _ nfdd_ t |d _ |d _|d _tjtrtj_|d _|d _|d_|d_|d_t|d\_}|d_|d_|d_|dpd_d_d|kr4|d_|d_|d_|d_ |d_!|d_"|d_#g_$t%|djjjd\}}j&'|t(|d r)|n|_d_*+\_,_-_.t/j,d!kr0j,j1j2\_,_1_2}t/j,_-n j,d_,t3j,_4j5sd6j,\}_4_,d"_7j1dkrd|_1j8rx9_:nd_:t/j"d!krt;d#j!dkrt<=d$j>j"d%_?nt<=d&j>j!j"d'_?dS)(z Workhorse function for processing nested list into DataFrame Should be replaced by np.genfromtxt eventually? NrrDrGrrhcs |jkS)N)rh)r!)rr<r=rirjz'PythonParser.__init__..rir^r`r_rbrcrdrarvr{rrrAFrrwrnrorqrsrrr)rDrGrreadlinerMTz'Only length-1 decimal markers supportedz[^-^0-9^{decimal}]+)rsz[^-^0-9^{thousands}^{decimal}]+)rqrs)@r rrZbufposline_posrDrGrrhrskipfuncrrir^r`rSrr_rbrcrdrar rvr{rrZ names_passedrrwrnrorqrsrrZ_comment_linesr-rextendr _make_reader _col_indices_infer_columnsrnum_original_columnsrr?r&rrrr r_get_index_namerrJ_set_no_thousands_columns_no_thousands_columnsr9rPcompiler7nonnum)rrrXrErrr<)rr=rs                                   zPythonParser.__init__cstfdd}tjtr\xƈjD].}t|trNx|D] }||q._set)r@rSrJrrrrf)rrcr:rer<)rrr=r5 s*           z&PythonParser._set_no_thousands_columnsc sljdkstdkrNjr*tdGfdddtj}|}d}dk rZd}|_|r}x&jrjd7_}qjW |gd}jd7_j d7_ t |}|j|_j dk rjttt||j dnjttjt||d j dk r.MyDialect N) rrrr^r`r_rbrcrardr<)rr<r= MyDialectb srTFr)rrD)r)rrDstrict)rrc3sD}t}||VxD]}||Vq(WdS)N)rvrPrsplitstrip)linepat)rrr<r=r[ s   z(PythonParser._make_reader.._read)r^r?rdr9rDialectrvrzrx_check_commentsrySniffersniffrDrwr{rr+rreaderrZ) rrrZdiaZ sniff_seprsniffedrr[r<)rrrr=r|Y sD     zPythonParser._make_readerNc Csy||}Wn"tk r0|jr*g}nYnXd|_t|j}t|s||j}t||j|j |j \}}}| ||j }|||fSt |d}d}|jr|t|kr|d}|dd}||} || } ||j}||| \}} || } || | ||\}}||| fS)NFrrM) _get_linesrrrr r?r+rmrfrror-rrur _rows_to_cols_exclude_implicit_indexrrZ _convert_datar4) rrowscontentrrArrZcount_empty_content_valsr3r2rZr<r<r=rV s4         zPythonParser.readcCsz||j}|jrb|j}i}d}xTt|D]2\}}x|||krJ|d7}q4W|||||<q*Wnddt||D}|S)NrrMcSsi|]\}}||qSr<r<)rrerkr<r<r=rl sz8PythonParser._exclude_implicit_index..)r+r r8rfrr#)rr2rAZ excl_indicesrZoffsetrrr<r<r=r s  z$PythonParser._exclude_implicit_indexcCs|dkr|j}|j|dS)N)r)rLrV)rrr<r<r=r szPythonParser.get_chunkc sfdd}|j}tjts*j}n |j}i}i}tjtrx^jD]F}j|}j|} t|tr|jkrj|}|||<| ||<qPWn j}j}|||j ||S)NcsDi}x:|D].\}}t|tr4|jkr4j|}|||<qW|S)zconverts col numbers to names)rrSr8r )mappingcleanrrk)rr<r=_clean_mapping s   z2PythonParser._convert_data.._clean_mapping) rnrSrorrjrr8r rNrw) rrZrZ clean_convZ clean_dtypesZclean_na_valuesZclean_na_fvaluesrZna_valueZ na_fvaluer<)rr=r s0        zPythonParser._convert_datac sj}d}d}t}jdk rj}t|tttjfr`t|dk}|rjt||ddg}n d}|g}g}xdt |D]V\}} y$ } xj | kr } qWWnt k r<j | krtdj| j dd|r| dkr|r|dgt|d|||fSjs*tdjdd} YnXgg} xbt | D]V\} } | d kr|rxd j| |d }n d j| d }| | |n | qPW|s*jr*tt}xt D]Z\} }||}x2|dkr |d||<dj||d}||}qW|| <|d||<qWnr|r| |dkrt}jdk r\tjnd}t| }||kr|||krd}dg|jdg_||fdd| Dt|dkrzt}qzW|r|dk r~jdk rt|tjks0jdkr8t|t|dkr8tdt|dkrNtdjdk rh||nd_t|}|g}n||d}ny } Wn0t k r|std|dd} YnXt| }|}|s$jrfddt|Dg}ntt|g}||d}nrjdks>t||krV|g|}t|}n@tjs~t|tjkr~td|g||g}|}|||fS)NrTrMrFz/Passed header={hr} but only {pos} lines in file)hrrxzNo columns to parse from filerzUnnamed: {i}_level_{level})rlevelz Unnamed: {i})rz{column}.{count})r'r(csh|] }|qSr<r<)rr) this_columnsr<r=ri sz.PythonParser._infer_columns..zHNumber of passed names did not match number of header fields in the filez*Cannot pass names with multi-index columnscsg|]}djj|dqS)z {prefix}{idx})rgr:)r7rg)rr)rr<r=r sz/PythonParser._infer_columns..) rAr@rerSrrrrr?r_buffered_linery _next_linerr9r7 _clear_bufferrr ryrr8rfrwrrvr_handle_usecolsr}rgrr)rrArZ clear_bufferrreZhave_mi_columnsrrrrZthis_unnamed_colsrrrCr)rr*lcr%Z unnamed_countZncolsr<)rrr=r~ s                  "     zPythonParser._infer_columnsc s|jdk rt|jr"t|j|ntdd|jDrt|dkrJtdgxb|jD]P}t|try| |Wqtk rt |j|YqXqV|qVWn|jfdd|D}|_ |S)zb Sets self._col_indices usecols_key is used if there are string usecols. Ncss|]}t|tVqdS)N)rSr)rur<r<r=r sz/PythonParser._handle_usecols..rMz4If using multiple headers, usecols must be integers.cs"g|]}fddt|DqS)csg|]\}}|kr|qSr<r<)rrr ) col_indicesr<r=r sz;PythonParser._handle_usecols...)r)rr')rr<r=r sz0PythonParser._handle_usecols..) rvrrrr?r9rSrrrrr})rrZ usecols_keyrr<)rr=r s(      zPythonParser._handle_usecolscCs$t|jdkr|jdS|SdS)zH Return a line from buffer, filling buffer if required. rN)r?rwr)rr<r<r=r s zPythonParser._buffered_linecCs|s|St|dts|S|ds&|S|dd}|tkr>|S|d}t|dkr|d|jkrd}|d}|dd|d}|||}t||dkr|||dd7}|g|ddSt|dkr|ddgSdgSdS)a- Checks whether the file begins with the BOM character. If it does, remove it. In addition, if there is quoting in the field subsequent to the BOM, remove it as well because it technically takes place at the beginning of the name, not the middle of it. rrMrNr)rSr_BOMr?r`r)rZ first_rowZ first_eltZ first_row_bomstartquoteendnew_rowr<r<r=_check_for_bom s*    zPythonParser._check_for_bomcCs| ptdd|DS)z Check if a line is empty or not. Parameters ---------- line : str, array-like The line of data to check. Returns ------- boolean : Whether or not the line is empty. css|] }| VqdS)Nr<)rr!r<r<r=r sz.PythonParser._is_line_empty..)r)rrr<r<r=_is_line_empty s zPythonParser._is_line_emptycCst|jtrx||jr*|jd7_qWxyn||j|jgd}|jd7_|jsz||j|jdsv|rzPn |jr||g}|r|d}PWq.t k rt Yq.Xq.Wnx(||jr|jd7_t |jqWxt|j |jdd}|jd7_|dk r||gd}|jrF||g}|rX|d}Pq||sV|rPqW|jdkrr| |}|jd7_|j||S)NrMr)row_num)rSrZrrzrxrr{r_remove_empty_lines IndexErrorrr_next_iter_linerryrwr)rrrZ orig_liner<r<r=r sJ      zPythonParser._next_linecCs:|jrt|n&|jr6dj|d}tj||ddS)a Alert a user about a malformed row. If `self.error_bad_lines` is True, the alert will be `ParserError`. If `self.warn_bad_lines` is True, the alert will be printed out. Parameters ---------- msg : The error message to display. row_num : The row number where the parsing error occurred. Because this row number is displayed, we 1-index, even though we 0-index internally. zSkipping line {row_num}: )rrN)rr rr7rstderrwrite)rr;rbaser<r<r=_alert_malformedR s   zPythonParser._alert_malformedc Csy t|jStjk r|}zR|js*|jrlt|}d|ksBd|krFd}|jdkr`d}|d|7}|||dSd}~XYnXdS)aL Wrapper around iterating through `self.data` (CSV source). When a CSV error is raised, we check for specific error messages that allow us to customize the error message displayed to the user. Parameters ---------- row_num : The row number of the line being parsed. z NULL bytezline contains NULzNULL byte detected. This byte cannot be processed in Python's native csv library at the moment, so please pass in engine='c' insteadrzError could possibly be due to parsing errors in the skipped footer rows (the skipfooter keyword is only applied after Python's csv library has parsed all rows).z. N) rrZrErrorrrrrir)rrer;rr<r<r=rg s      zPythonParser._next_iter_linecCs|jdkr|Sg}xt|D]l}g}xX|D]P}t|tr>|j|krJ||q&|d||j}t|dkrt||Pq&W||qW|S)Nr)rrrSrrfindr?)rlinesrlrlr!r<r<r=r s      zPythonParser._check_commentscCsRg}xH|D]@}t|dks@t|dkr t|dtr@|dr ||q W|S)a} Iterate through the lines and remove any that are either empty or contain only one whitespace value Parameters ---------- lines : array-like The array of lines that we are to filter. Returns ------- filtered_lines : array-like The same array of lines with the "empty" ones removed. rMr)r?rSrrr)rrrrr<r<r=r s   z PythonParser._remove_empty_linescCs |jdkr|S|j||jddS)Nr)rsearchreplace)rq_search_replace_num_columns)rrr<r<r=_check_thousands s zPythonParser._check_thousandsc Csg}x|D]x}g}xdt|D]X\}}t|trV||ksV|jrF||jksV|j|rb||q||||qW||q W|S)N) rrSrrrrrrr) rrrrrrrrr!r<r<r=r s   z(PythonParser._search_replace_num_columnscCs$|jtdkr|S|j||jddS)Nrs.)rrr)rsrr)rrr<r<r=_check_decimal szPythonParser._check_decimalcCs g|_dS)N)rw)rr<r<r=r szPythonParser._clear_bufferFc CsLt|}t|}y |}Wntk r4d}YnXy |}Wntk rZd}YnXd}|dk r|jdk rt||j}|dk rt|t||jkrttt||_|jdd|_xt|D]}| d|qWt|}t||_|||fS|dkr*d|_ |jdkr$tt||_d}nt ||j|j \}}|_|||fS)a Try several cases to get lines: 0) There are headers on row 0 and row 1 and their total summed lengths equals the length of the next line. Treat row 0 as columns and row 1 as indices 1) Look for implicit index: there are more columns on row 1 than row 0. If this is true, assume that row 1 lists index columns and row 0 lists normal columns. 2) Get index from the columns if it was listed. NrFrMT) rrrrfr?rrrwr6insertr8r"r) rrr rZ next_lineZimplicit_first_colsrZ index_nameZcolumns_r<r<r=r s>          zPythonParser._get_index_namecsj}jr|tj7}tdd|D}||krDjdk rDjdkrDjrZjnd}g}t|}t|}g}x`|D]X\}} t| } | |krʈjsj rԈj |||} | | | fjrPq|| | q|Wxj|D]b\} } dj || d| d} j r0tj dkr0jtjkr0d} | d | 7} | | dqWttj||d j}jrjrfd d t|D}nfd d t|D}|S)Ncss|]}t|VqdS)N)r?)rrowr<r<r=r' sz-PythonParser._rows_to_cols..Frz6Expected {col_len} fields in line {line}, saw {length}rM)col_lenrlengthzXError could possibly be due to quotes being ignored when a multi-char delimiter is used.z. )Z min_widthcs6g|].\}}|tjks.|tjjkr|qSr<)r?rfr})rra)rr<r=r] sz.PythonParser._rows_to_cols..csg|]\}}|jkr|qSr<)r})rrr)rr<r=rf s)rr8r?rfmaxrvrirrrrxrr7r^rar QUOTE_NONErrrZto_object_arrayT)rrrmax_lenZfootersZ bad_lines iter_contentZ content_lenrrZ actual_lenrr;rZzipped_contentr<)rr=r! sF"   zPythonParser._rows_to_colscs"j}d}|dk rPtj|krBjd|j|d}_n|tj8}|dkrtjtrjtjkrzt|dkrjjd}tj}n jjj|}j|}jrڇfddt|D}| ||_ng}y||dk r,x"t |D]}| t jqW| |n>d}x8j j|dd}|d7}|dk r2| |q2WWnNtk rjrfddt|D}| |t|dkrYnXjt|7_g_n|}jr|dj }|}jr|}|}|S)Ncs$g|]\}}|js|qSr<)rzrx)rrr)rr<r=r sz+PythonParser._get_lines..rrM)rcs$g|]\}}|js|qSr<)rzrx)rrr)rr<r=r s)rwr?rSrZrrxrrhrr{rrrrrirr{rrr)rrrrnew_posrErr<)rr=rj sb"                zPythonParser._get_lines)N)N)N)rrrrrr|rVrrrr~rrrrrrrrrrrrrr8rrrr<r<r<r=rs4~$G ( -$" 54(@Ircsfdd}|S)Nc sdkr\t|}ytjt|dddStk rXtjtj|ddSXny,tj|dd}t|t j rt d|St k ry tjtjt|dddSt k rt f|SXYnXdS) Nignore)utcruerrorsrzcache)ru)r)rrz scalar parser)rYru)r) rZ_concat_date_colstoolsZ to_datetimerZto_numpyr9r.rSdatetimerSr2) date_colsstrsr)rprIrurzr<r= converter s:   z'_make_date_converter..converterr<)rIrurzrprr<)rprIrurzr=r s'rcsfdd}g}i} |} t|}t} |dks:t|trB||fSt|trx|D]} t| rt| trx| |krx| | } || rqR||| || <qRt|| || \} }}| |krtdj| d|| | <| | | |qRWnlt|t rNx^| D]R\} } | |krtdj| dt|| || \}}}|| | <| | | |qW| | | ||sx&t| D]}||||qrW||fS)Ncs$ttr|kp"tto"|kS)N)rSr)colspec)rfrr<r=_isindex sz*_process_date_conversion.._isindexz&New date column already in dict {name})r5z"Date column {name} already in dict)rr@rSrTrr8_try_convert_datesr9r7rrrrr{rr=) data_dictrZ parse_specrfrrrtrZnew_colsZnew_datar rrnew_namerZ old_namesrErr<)rfrr=rY sR          rYc st|}g}xL|D]D}||kr*||qt|trL||krL|||q||qWddd|D}fdd|D}||} || |fS)NrEcss|]}t|VqdS)N)r)rr!r<r<r=r; sz%_try_convert_dates..csg|]}|kr|qSr<r<)rr)rr<r=r< sz&_try_convert_dates..)r@rrSr8r) rYrrrcolsetcolnamesrrto_parseZnew_colr<)rr=r/ s  rcCs|dkr |rt}nt}t}nt|tr|}i}x:|D].\}}t|sV|g}|rft|tB}|||<q@Wdd|D}n*t|s|g}t|}|r|tB}t|}||fS)NcSsi|]\}}t||qSr<)_floatify_na_values)rrerkr<r<r=rlZ sz$_clean_na_values..) r)r@rSrrrr_stringify_na_valuesr)rjrkrZ old_na_valuesrerkr<r<r=rB s,   rc Cst|sd||fSt|}t|}g}t|}xxt|D]l\}}t|tr||xNt|D]$\}}||kr^|||<||Pq^Wq8||}||||q8Wx.t|D]"\}}t|tr||krd||<qW|||fS)N)rrrrSrrr=) rrfrZcp_colsrrrrr5r<r<r=r"g s*      r"c st|}tts.ptjtfddnF}tddx0|D]$\}}t|rd||n|}||<qLW|dks|dks|dkrt g}nJfdd|D} t | |d}| x"t |D]\} } | | | qWfdd |D} ||| fS) NcsS)Nr<r<) default_dtyper<r=ri rjz!_get_empty_meta..cSstjS)N)robjectr<r<r<r=ri rjFcsg|]}tg|dqS))ro)r')rr5)ror<r=r sz#_get_empty_meta..)rAcsi|]}tg|d|qS))ro)r')rrC)ror<r=rl sz#_get_empty_meta..)rrSrrrrrrrr#r&rdrr) rrfrroZ_dtypererkrrrZrr rr<)rror=rm s$      rmc CsTt}xH|D]@}y t|}t|s.||Wq tttfk rJYq Xq W|S)N)r@floatrisnanrrr9 OverflowError)rjrrkr<r<r=r s   rc Csg}x|D]}|t|||yJt|}|t|krdt|}|dj|d|t|||Wntttfk rYnXy|t|Wq tttfk rYq Xq Wt|S)z3 return a stringified and numeric for these values z {value}.0)r) rrrr8r7rr9rr@)rjrr!rkr<r<r=r s$    rcCsJt|tr>||kr"||||fS|r0ttfSttfSn||fSdS)a Get the NaN values for a given column. Parameters ---------- col : str The name of the column. na_values : array-like, dict The object listing the NaN values as strings. na_fvalues : array-like, dict The object listing the NaN values as floats. keep_default_na : bool If `na_values` is a dict, and the column is not mapped in the dictionary, whether to return the default NaN values or the empty set. Returns ------- nan_tuple : A length-two tuple composed of 1) na_values : the string NaN values for that column. 2) na_fvalues : the float NaN values for that column. N)rSrr)r@)rrjrrkr<r<r=r> s  r>cCsJt|}g}x8|D]0}||kr*||qt|tr|||qW|S)N)r@rrSr8)rrrrrr<r<r=_get_col_names s   rc@s6eZdZdZd ddZd ddZddd Zd d ZdS)FixedWidthReaderz( A reader of fixed-width lines. NrcCs||_d|_|rd|nd|_||_|dkr>|j||d|_n||_t|jttfsft dt |j xd|jD]Z}t|ttfrt |dkrt|dt tjt dfrt|dt tjt dfsnt d qnWdS) Nz z rH)rrhz=column specifications must be a list or tuple, input was a %rrrrMzEEach column specification must be 2 element tuple or list of integers)rbufferr^rrdetect_colspecsrrSrrrrrr?r8rr)rrrr^rrrhrrr<r<r=rs&  zFixedWidthReader.__init__cCsf|dkrt}g}g}x@t|jD]2\}}||kr<||||t||kr"Pq"Wt||_|S)a Read rows from self.f, skipping as specified. We distinguish buffer_rows (the first <= infer_nrows lines) from the rows returned to detect_colspecs because it's simpler to leave the other locations with skiprows logic alone than to modify them to deal with the fact we skipped some rows here as well. Parameters ---------- infer_nrows : int Number of rows to read from self.f, not counting rows that are skipped. skiprows: set, optional Indices of rows to skip. Returns ------- detect_rows : list of str A list containing the rows to read. N)r@rrrr?rr)rrrhZ buffer_rowsZ detect_rowsrrr<r<r=get_rows,s    zFixedWidthReader.get_rowsc sdddjD}td|}||}|s>tdttt |}t j |dt d}j dk rzfdd |D}x4|D],}x&||D]} d|| | <qWqWt |d} d | d <t || Adkd } tt| ddd | ddd } | S) Nrcss|]}d|VqdS)z\{}N)r7)rr!r<r<r=rTsz3FixedWidthReader.detect_colspecs..z([^{}]+)z(No rows from which to infer column widthrM)rocsg|]}|jdqS)r) partitionrr)rr)rr<r=r\sz4FixedWidthReader.detect_colspecs..rr)rr^rPrr7rr rrr?rzerosr8rrfinditerrrZrollwhererr#) rrrh delimiterspatternrrrLrmZshiftededgesZ edge_pairsr<)rr=rRs"    "z FixedWidthReader.detect_colspecscs`jdk r@ytjWqJtk r<d_tjYqJXn tjfddjDS)Ncs$g|]\}}||jqSr<)rr^)rZfrommto)rrr<r=rpsz-FixedWidthReader.__next__..)rrrrr)rr<)rrr=rfs  zFixedWidthReader.__next__)Nr)N)rN)rrrrrrrrr<r<r<r=r s   & rc@s eZdZdZddZddZdS)rzl Specialization that Converts fixed-width fields into DataFrames. See PythonParser for details. cKs,|d|_|d|_tj||f|dS)Nrr)rrrrr)rrrXr<r<r=rys  zFixedWidthFieldParser.__init__cCs"t||j|j|j|j|j|_dS)N)rrr^rrrhrrZ)rrr<r<r=r|sz"FixedWidthFieldParser._make_readerN)rrrrrr|r<r<r<r=rssr)r)r)rHNr)NFFT)F)T)N)r collectionsrrriorrPrtextwraprtypingrrrrZnumpyrZpandas._libs.libZ_libsrZpandas._libs.opsopsrUZpandas._libs.parsersrTZpandas._libs.tslibsrZ pandas.errorsr r r r Zpandas.util._decoratorsr Zpandas.core.dtypes.castrZpandas.core.dtypes.commonrrrrrrrrrrrrrrZpandas.core.dtypes.dtypesrZpandas.core.dtypes.missingrZpandas._typingrZ pandas.corer Zpandas.core.arraysr!Zpandas.core.framer"Zpandas.core.indexr#r$r%r&Zpandas.core.seriesr'Zpandas.core.toolsr(rZpandas.io.commonr)r*r+r,r-r.r/r0r1Zpandas.io.date_convertersr2rrr7Z_doc_read_csv_and_tabler>rBr[rrrrrrrr@rrrr7rrrUrrrrrr r r rrsrurrrYrrr"rmrrr>rrrr<r<r<r=s$      @        , x. 4    O  2: 3 B %! , $ j