U Dx`A"2@sUdZddlmZmZddlZddlZddlmZddlZddl Z ddl Z ddl m Z ddl mZmZmZmZmZmZmZmZmZmZddlZddlZddlmmZddlmmZ ddl!mm"Z"ddl!m#Z#ddl$m%Z%dd l&m'Z'm(Z(m)Z)dd l*m+Z+m,Z,m-Z-m.Z.dd l/m0Z0dd l1m2Z2dd l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCddlDmEZEddlFmGZGddlHmIZImJZJddlKmLZLddlMmNZNddlOmPZPmQZQmRZRmSZSddlTmUZUddlVmWZXddlYmZZZm[Z[m\Z\ddl]m^Z^dZ_de d`eae#ddddZbddd Zcd!d"Zde'd#d$d%Zeddd&ejfd'd(dd)dddddddd'ddddd'ddd*d(d(d(dddd(dd(dd'd(d'd+%Zgd(d'd'd(d'd'dd,Zhd)d-dd.Zid/hZjd0d1hZkiZleemefend2<eoZpeemend3<e0ebjqd4d5d6eJjrd7d8ejsdd)dddd(dd'dddddd(ddddd'd'd(d'd(d(d(dd(d'd(dd)dd*dd&ejfd'ddddd'd'd(ehd0d(ddf1e'eme(d9d:d4Zte0ebjqd;dd?d;Zude'd#d@dAZvGdBdCdCejZwdDdEZxdee)eyeezfdFdGdHZ{dIdJZ|dKdLZ}dMdNZ~dOdPZdQdRZGdSdTdTZGdUdVdVeZdWdXZezdYdZd[ZGd\d]d]eZdd^d_Zdd`daZdbdcZddddeZdfdgZddhdiZdjdkZdldmZdndoZdpdqZGdrdsdsejZGdtdudueZe)emejfe)emefeyeme)emefeemefdvdwdxZeemefeejdydzd{Zd|Zejdd}d~dZejeemefeemefdddZeemefddyddZdS)zM Module contains tools for processing files into DataFrames or other objects )abc defaultdictN)StringIO)fill) AnyDictIterableIteratorListOptionalSequenceSetTypecast) STR_NA_VALUES)parsing)FilePathOrBufferStorageOptionsUnion)AbstractMethodErrorEmptyDataError ParserError ParserWarning)Appender)astype_nansafe) ensure_object ensure_str is_bool_dtypeis_categorical_dtype is_dict_likeis_dtype_equalis_extension_array_dtype is_file_likeis_float is_integeris_integer_dtype is_list_likeis_object_dtype is_scalaris_string_dtype pandas_dtype)CategoricalDtype)isna) algorithmsgeneric) Categorical) DataFrame)Index MultiIndex RangeIndexensure_index_from_sequencesSeries) datetimes) IOHandles get_handlevalidate_header_arg)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, gs, 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 handle (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 the file contains a header row, then you should explicitly pass ``header=0`` to override the column names. 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 unparsable 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 : bool, 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()``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs `_ for more information on ``iterator`` and ``chunksize``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. 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. 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 `_ . .. versionchanged:: 1.2 When ``encoding`` is ``None``, ``errors="replace"`` is passed to ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``. This behavior was previously only the case for ``engine="python"``. 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. 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`` or 'high' for the ordinary converter, 'legacy' for the original lower precision pandas converter, and 'round_trip' for the round-trip converter. .. versionchanged:: 1.2 {storage_options} .. versionadded:: 1.2 Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.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 cCs^d|dd|d}|dk rZt|rBt||kr8t|t|}nt|rR||ksZt||S)a Checks whether the 'name' parameter for parsing is either an integer OR float that can SAFELY be cast to an integer without losing accuracy. Raises a ValueError if that is not the case. Parameters ---------- name : string Parameter name (used for error reporting) val : int or float The value to check min_val : int Minimum allowed value (val < min_val will result in a ValueError) 'sz' must be an integer >=dN)r#int ValueErrorr$)namevalZmin_valmsgrF8/tmp/pip-target-zr53vnty/lib/python/pandas/io/parsers.pyvalidate_integers  rHcCsH|dk rDt|tt|kr$tdt|ddsDt|tjsDtddS)aZ Raise ValueError if the `names` parameter contains duplicates or has an invalid data type. Parameters ---------- names : array-like or None An array containing a list of the names used for the output DataFrame. Raises ------ ValueError If names are not unique or are not ordered (e.g. set). Nz Duplicate names are not allowed.F)Z allow_setsz&Names should be an ordered collection.)lensetrBr& isinstancerKeysViewnamesrFrFrG_validate_namess  rO)filepath_or_bufferc Cs|dddk r&t|dtr&d|d<|dd}td|ddd}|d d}t|d dt|f|}|sv|rz|S|||W5QRSQRXdS) zGeneric reader of line files. date_parserN parse_datesTiteratorF chunksizenrowsrN)getrKboolrHrOTextFileReaderread)rPkwdsrSrTrVparserrFrFrG_reads   r]"TFinfer.)% delimiter escapechar quotecharquoting doublequoteskipinitialspacelineterminatorheader index_colrNprefixskiprows skipfooterrV na_valueskeep_default_na true_values false_values convertersdtype cache_dates thousandscommentdecimalrR keep_date_coldayfirstrQusecolsrTverboseencodingsqueeze compressionmangle_dupe_colsinfer_datetime_formatskip_blank_lines)delim_whitespace na_filter low_memory memory_maperror_bad_lineswarn_bad_linesfloat_precisiond)colspecs infer_nrowswidthsrlrr_deprecated_defaults_deprecated_argsread_csvz8Read a comma-separated values (csv) file into DataFrame.z','storage_options) func_namesummaryZ _default_sepr)rPrvrc24Cs>t}2|2d=|2d=t|*||-| |ddid}3|2|3t||2S)NrPsepra,defaultslocals_refine_defaults_readupdater])4rPrrarhrNriryr|rjr~rrenginerqrorprfrkrlrVrmrnrrzrrRrrwrQrxrsrSrTr}rtrvrgrcrdrerbrur{dialectrrrrrrrr[ kwds_defaultsrFrFrGrsD  read_tablez+Read general delimited file into DataFrame.z'\\t' (tab-stop))rPrvc13Cs>t}1|1d=|1d=t|*||-| |ddid}2|1|2t||1S)NrPrra rr)3rPrrarhrNriryr|rjr~rrrrqrorprfrkrlrVrmrnrrzrrRrrwrQrxrsrSrTr}rtrvrgrcrdrerbrur{rrrrrrrr[rrFrFrGresC cKs|dkr|dkrtdn|dkr2|dk r2td|dk rhgd}}|D]}||||f||7}qH||d<||d<d|d <t||S) aW 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 handle (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 -------- DataFrame.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)Nr_z4You must specify only one of 'widths' and 'colspecs'rrr python-fwfr)rBappendr])rPrrrr[colwrFrFrGread_fwfs?   rc@sxeZdZdZdddZddZddZd d Zd d Zd dZ dddZ ddZ dddZ dddZ ddZddZdS) rYzF Passed dialect overrides any of the related parser options NcKs||_|dk rd}nd}d}||_|d||_t|t|}|dk rRt||}|dddkr||ddkrtdnd|d<||_d|_| |}|d d|d <| d d|_ | d d|_ | d d|_ ||||||\|_|_d |kr|d |jd <||j|_dS)NTpythonFengine_specifiedrhr_rNrrrTrVr|has_index_names)frrW_engine_specified_validate_skipfooter_extract_dialect_merge_with_dialect_properties orig_options_currow_get_options_with_defaultspoprTrVr|_check_file_or_buffer_clean_optionsoptions _make_engine_engine)selfrrr[rrrrFrFrG__init__ s2    zTextFileReader.__init__cCs|jdSN)rcloserrFrFrGr5szTextFileReader.closecCs|j}i}tD]2\}}|||}|dkr<|s} |r|| t| krt d|dt| d|| =q|rtjd|dtdd|d} |d} |d} |d}|d}t|d tD]N} t| }t| }|| ||krd!| d"}tj|td#dn||| <qF| d krt d$t| rt| tttjfs| g} | |d<| dk rt| n| } | dk rt| tstd%t| j ni} |d&}t!||\}}|dkrtt"|rPtt#|}|dkrbt$}nt%|stt$|}| |d<| |d<||d<||d'<||d<||fS)(Nrrlrz*the 'c' engine does not support skipfooterrrarzDthe 'c' engine does not support sep=None with delim_whitespace=FalserUz\s+T)rrzxthe 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)zutf-8Fzthe separator encoded in zF is > 1 char long, and the 'c' engine does not support such separatorsrczxord(quotechar) > 127, meaning the quotechar is larger than one byte, and the 'c' engine does not support such quotecharsz,Falling back to the 'python' engine because z, but this causes z= to be ignored as it is not supported by the 'python' engine.z;; you can avoid this warning by specifying engine='python'. stacklevelrirNrqrmrkrhrzH argument has been deprecated and will be removed in a future version. z)The value of index_col couldn't be 'True'z8Type converters must be a dict or subclass, input was a rn na_fvalues)&copyrIsysgetfilesystemencodingencodeUnicodeDecodeErrorrKstrbytesordrrB_c_unsupportedrrrwarningswarnrr:rrrW FutureWarning _is_index_collisttuplenpndarraydict TypeErrortype__name___clean_na_valuesr$rangerJcallable)rrrresultZfallback_reasonrrZ encodeabler{rcargrirNrqrmrkparser_defaultZ depr_defaultrErnrrFrFrGrls                           zTextFileReader._clean_optionscCs.z |WStk r(|YnXdSr) get_chunk StopIterationrrrFrFrGrs  zTextFileReader.__next__rcCsBtttd}||kr.td|d|d|||jf|jS)N)rrrzUnknown engine: z (valid options are ))CParserWrapper PythonParserFixedWidthFieldParserrBkeysrr)rrmappingrFrFrGrszTextFileReader._make_enginecCs t|dSr)rrrFrFrG_failover_to_pythonsz"TextFileReader._failover_to_pythoncCstd|}|j|\}}}|dkrV|rPttt|}t|j|j|}q^d}nt|}t |||d}|j|7_|j rt|j dkr||j d S|S)NrVr)columnsindexrU) rHrrZrInextitervaluesr3rr0r|rr)rrVrrcol_dictnew_rowsZdfrFrFrGrZs zTextFileReader.readcCsF|dkr|j}|jdk r:|j|jkr(tt||j|j}|j|dS)N)rV)rTrVrrminrZrsizerFrFrGr5s  zTextFileReader.get_chunkcCs|SrrFrrFrFrG __enter__>szTextFileReader.__enter__cCs |dSr)r)rexc_type exc_value tracebackrFrFrG__exit__AszTextFileReader.__exit__)N)r)N)N)r __module__ __qualname____doc__rrrrrrrrrZrrrrFrFrFrGrYs ))    rYcCs|dk o|dk S)NFrFrrFrFrGrEsrrics@dksttrgt|o>t|t o>tfdd|DS)a 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 index_col : None, bool or list, optional Column or columns to use as the (possibly hierarchical) index Returns ------- boolean : Whether or not columns could become a MultiIndex Nc3s$|]}|tkrt|tVqdSr)rrKr.0rrrFrG as z,_is_potential_multi_index..)rKrXrIr2all)rrirFrrG_is_potential_multi_indexIs r cs"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|qSrFrFrirCryrFrG nsz$_evaluate_usecols..)r enumerate)ryrNrFr rG_evaluate_usecolsesrcs0fdd|D}t|dkr,td||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|qSrFrFrrMrFrG sz+_validate_usecols_names..rz>Usecols do not match columns, columns expected but not found: )rIrB)ryrNmissingrFrMrG_validate_usecols_namesrs  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)r$rB)rlrFrFrG_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)emptyintegerstring)rr&rBlibZ infer_dtyperJ)ryrE usecols_dtyperFrFrG_validate_usecols_argsrcCsBd}|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)r(rZis_boolrrKrr)rRrErFrFrG_validate_parse_dates_args  rc@seZdZddZeeeefddddZe edddd Z d d Z e d d Z ddZd)ddZddZd*ddZd+ddZdZddZddZd,eddd Zd-d!d"Zd.d#d$Zd%d&Zd'd(ZdS)/ ParserBasecCs@|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#dnL|jdk r*|jdk rt#dn*t"|jst#dn|jdkr*t#dd|_%d |_&d|_'dS) NrNrjrirRFrQrxrwrmrrrnTrorpr~rrs)rQrxrrsrhz*header must be integer or list of integerscss|]}|dkVqdSrNrFrr rFrFrGrsz&ParserBase.__init__..z8cannot specify multi-index header with negative integersryz;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 headerz;Argument prefix must be None if argument header is not NonerzUPassing negative integer to header is invalid. For no header, use header=None instead)(rWrN orig_namesrrjrirJ unnamed_cols index_names col_namesrrRrQrxrwrmrrrnrorpr~rrs_make_date_converter _date_convrhrKrrrrrmapr$rBany_name_processed _first_chunkhandles)rr[Z is_sequencerFrFrGrs              zParserBase.__init__N)srcr[returnc Cs:t|d|dd|dd|dd|ddd|_dS) za Let the readers open IOHanldes after they are done with their potential raises. rr{Nr}rFr)r{r}rr)r9rWr))rr*r[rFrFrG _open_handlesNs    zParserBase._open_handles)rr+csxt|jrtj|j}n(t|jr@tjdd|jD}ng}dtfdd|D}|rtt d|ddS) ao Check if parse_dates are in columns. If user has provided names for parse_dates, check if those columns are available. Parameters ---------- columns : list List of names of the dataframe. Raises ------ ValueError If column to parse_date is not in dataframe. css |]}t|r|n|gVqdSr)r&rrrFrFrGrvsz.z, cs"h|]}t|tr|kr|qSrFrKrr.rrFrGr s z.z+Missing column provided to 'parse_dates': 'r>N) rrR itertoolschainrr& from_iterablejoinsortedrB)rrZ cols_neededZ missing_colsrFr0rG_validate_parse_dates_presence[s$       z)ParserBase._validate_parse_dates_presencecCs|jdk r|jdSr)r)rrrFrFrGrs zParserBase.closecCs6t|jtp4t|jto4t|jdko4t|jdtSNr)rKrRrrrIrrFrFrG_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||jkSdSr)rKrRrXr!rir()rr rCjrFrFrG_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}||}t t|dD]Bt fd d|Drd d djD}td |d qt|rfdd|D}ndgt|}d}||||fS)z extract and return the names, index_names, col_names header is a list-of-lists returned from the parsers rrNcstfddtDS)Nc3s|]}|kr|VqdSrrFr)r,sicrFrGrszMParserBase._extract_multi_indexer_columns..extract..)rrr,) field_countr<r=rGextractsz:ParserBase._extract_multi_indexer_columns..extractc3s|]}|VqdSrrFrr,)r?rFrGrsz.c3s |]}t|jkVqdSr)rr r.)nrrFrGrsrcss|]}t|VqdSrrrxrFrFrGrszPassed header=[z3] are too many rows for this multi_index of columnscs2g|]*}|ddk r*|djkr*|dndqSr)r r@rrFrGrsz=ParserBase._extract_multi_indexer_columns..T)rIrirKrrrrrJr_clean_index_namesr ziprrr4rhr) rrhr!r" passed_namesicrNrirrF)r?r>rArr<rG_extract_multi_indexer_columnss>       z)ParserBase._extract_multi_indexer_columnscCs|jrt|}tt}t||j}t|D]v\}}||}|dkr|d||<|rt|dd|dd|f}n|d|}||}q:|||<|d||<q*|S)NrrUr;r`)r~rrrAr rir)rrNcountsZis_potential_mir r cur_countrFrFrG_maybe_dedup_namess  " zParserBase._maybe_dedup_namescCst|rtj||d}|S)NrM)r r2 from_tuples)rrr"rFrFrG_maybe_make_multi_index_columnssz*ParserBase._maybe_make_multi_index_columnscCst|jr|jsd}nh|js4|||}||}nJ|jr~|jsdtt||j|j\|_ }|_d|_| ||}|j|dd}|rt |t |}| |d|}| ||j}||fS)NTFtry_parse_dates)rrir8_get_simple_index _agg_indexr'rErr r!_get_complex_date_indexrIZ set_namesrNr")rdataalldatar indexnamerowr_ZcoffsetrFrFrG _make_index s(   zParserBase._make_indexcCsldd}g}g}|jD]$}||}|||||qt|ddD]}|||jsH||qH|S)NcSs"t|ts|Std|ddS)NzIndex z invalid)rKrrBrrFrFrGix(s z(ParserBase._get_simple_index..ixTreverse)rirr5r_implicit_index)rrTrrY to_removeridxr rFrFrGrQ's    zParserBase._get_simple_indexc sjfdd}g}g}|jD]$}||}|||||qt|ddD]}|||qL|S)NcsLt|tr|Sdkr&td|dtD]\}}||kr.|Sq.dS)Nz Must supply column order to use z as index)rKrrBr)Zicolr rr"rFrG _get_name>s z5ParserBase._get_complex_date_index.._get_nameTrZ)rirr5rremove) rrTr"r`r]rr^rCrrFr_rGrS=s     z"ParserBase._get_complex_date_indexTr+c Csg}t|D]\}}|r,||r,||}|jr@|j}|j}n t}t}t|jtr|j |}|dk rt ||j|j|j \}}| |||B\}} | |q |j } t|| }|Sr)rr:r$rrmrrJrKrr!_get_na_valuesrn _infer_typesrr4) rrrParraysr Zarr col_na_valuescol_na_fvaluescol_namerWrNrFrFrGrRXs.     zParserBase._agg_indexc Csi}|D]\}} |dkr"dn ||d} t|trF||d} n|} |jrft||||j\} } ntt} } | dk r| dk rtj d|dt ddzt | | } Wn:t k rt| t|tj}t | | |} YnX|j| t| | Bdd\}}nt| }|pt| }| o&| }|| t| | B|\}}| rt|| r`t| r|s|dkrzt| rt d|Wnttfk rYnX||| |}|||<|r |r td |d |q |S) Nz5Both a converter and dtype were specified for column z" - only the converter will be usedrF) try_num_boolrz$Bool column has NA values in column zFilled z NA values in column )rrWrKrrrcrnrJrrrrZ map_inferrBr-isinrviewrZuint8Zmap_infer_maskrdr!r)r rAttributeErrorr _cast_typesprint)rdctrmrrzrqZdtypesrrrZconv_f cast_typerfrgmaskZcvalsna_countZis_eaZis_str_or_ea_dtyperjrFrFrG_convert_to_ndarraysxsr          zParserBase._convert_to_ndarraysc Csd}t|jjtjtjfrft|t|}| }|dkr^t |rN| tj }t ||tj||fS|rt|jrzt||d}Wn*ttfk r|}t||d}YqXt| }n|}|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)rorp) issubclassrrrrnumberZbool_r-rkrsumr%Zastypefloat64Zputmasknanr'rZmaybe_convert_numericrBrparsersZsanitize_objectsr,Zobject_libopsZmaybe_convert_boolZasarrayrorp)rrrmrjrsrrrrFrFrGrds4  zParserBase._infer_typesc Cst|r^t|to|jdk }t|s2|s2t|t}t| }t j || |||j d}nt|rt|}|}z|j||dWStk r}ztd|d|W5d}~XYnXnPzt||ddd}Wn:tk r }ztd|d ||W5d}~XYnX|S) aF Cast values to specified type Parameters ---------- values : ndarray cast_type : string or np.dtype dtype to cast values to column : string column name - used only for error reporting Returns ------- converted : ndarray N)rorrzExtension Array: zO must implement _from_sequence_of_strings in order to be used in parser methodsT)rrzUnable to convert column z to type )rrKr+ categoriesr'rrr1uniqueZdropnar/Z_from_inferred_categoriesZ get_indexerror!r*Zconstruct_array_typeZ_from_sequence_of_stringsNotImplementedErrorrB)rrrqcolumnZ known_catsZcatsZ array_typeerrrFrFrGrnsB    zParserBase._cast_typesc Cs6|jdk r.t||j|j|j|j||jd\}}||fS)N)rw)rR_process_date_conversionr$rir!rw)rrNrTrFrFrG_do_date_conversions+s  zParserBase._do_date_conversions)F)N)F)T)FNN)T)rrrrrrrrr-r r6rpropertyr8r:rIrLrNrXr\rQrSr1rRrtrdrnrrFrFrFrGrs.V 0  ;  ! I 37rcsdeZdZedddZddfdd Zdd Zd d Zdd d ZddZ ddZ dddZ Z S)r)r*c s|_|}t|jdk |d<t|d\__j|d<||j dk s`t dD]}| |dqdj j rt j jdrj jjj _ztjj jf|_Wn tk rj YnXjj_jdk}jjdkrd_nLtjjdkr6jjjj|\___}ntjjd_jdkrjrzfdd tjjD_nttjj_jdd_ jr:t!jj j dk st jd krt"#j st$j tjtkrfd d t%jD_tjtkr:t$j&j'j_ j(s҈jj)dkrt*jrd _+t,jjj\}__jdkr|_jjdkr|sdgtj_jj)dk_-dS) NFZallow_leading_colsry)rr{rr}mmaprUrcsg|]}j|qSrFrjrrrFrGrsz+CParserWrapper.__init__..rcs$g|]\}}|ks|kr|qSrFrFrr rAr rFrGrsT).r[rrrrirryrr-r)AssertionErrorrZis_mmaprhandlerrzZ TextReader_reader Exceptionrr rNrhrIrIr!r"rrjrZ table_widthrrrJissubsetrrr6_set_noconvert_columnsr8 leading_colsrr'rEr\)rr*r[keyrGr!rF)rryrGr=s                 zCParserWrapper.__init__Nrbcs2tz|jWntk r,YnXdSr)superrrrBr __class__rFrGrs  zCParserWrapper.closecs&jjdkr$tjn(tjs8jdkrHjddndfdd}tjtrjD]*}t|tr|D] }||qqn||qnntjt rj D]*}t|tr|D] }||qq||qnBjr"tj tr j D] }||qnj dk r"|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)rNNcsFdk rt|r|}t|s6dk s,t|}j|dSr)r$rrrZ set_noconvertrDrNrryrFrG_sets   z3CParserWrapper._set_noconvert_columns.._set) rrrrysortrrNrKrRrrrirrrDkrFrrGrs4               z%CParserWrapper._set_noconvert_columnscCs|jt|dSr)rset_error_bad_linesrA)rstatusrFrFrGrsz"CParserWrapper.set_error_bad_linesc s(z|j|}Wntk r|jrd|_||j}t||j|j|j dd\}}| |j |j dk r||fdd|D}||fYS|YnXd|_|j}|jjr|jrtdg}t|jjD]F}|jdkr||}n||j|}|j||dd}||qt|}|j dk rJ||}||}t|}d dt||D}|||\}}nt|}|jdk stt|j}||}|j dk r||}d d |D} d dt||D}|||\}}||| |\}}| ||j }|||fS) NFrrr|csi|]\}}|kr||qSrFrFrrvr0rFrG sz'CParserWrapper.read..z file structure not yet supportedTrOcSsi|]\}\}}||qSrFrFrrr rrFrFrGrCs cSsg|] }|dqS)rUrFrCrFrFrGrVsz'CParserWrapper.read..cSsi|]\}\}}||qSrFrFrrFrFrGrXs ) rrZrr(rLr_get_empty_metarir!r[rWrNr"ry_filter_usecolsrrrNrr8rrr_maybe_parse_datesrr4r5rFrrrrX) rrVrTrNrrrer rrUrFr0rGrZ sd                 zCParserWrapper.readcs>t|j|dk r:t|tkr:fddt|D}|S)Ncs$g|]\}}|ks|kr|qSrFrFr r rFrGrfsz2CParserWrapper._filter_usecols..)rryrIr)rrNrFr rGrbs   zCParserWrapper._filter_usecolscCsJt|jjd}d}|jjdkrB|jdk rBt||j|j\}}|_||fSr7)rrrhrrirEr )rrNZ idx_namesrFrFrG_get_index_namesks zCParserWrapper._get_index_namesTcCs|r||r||}|Sr)r:r$)rrrrPrFrFrGrvs z!CParserWrapper._maybe_parse_dates)N)T) rrrrrrrrrZrrr __classcell__rFrFrrGr<s < W  rcOsd|d<t||S)av 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` or `high` for the ordinary converter, `legacy` for the original lower precision pandas converter, and `round_trip` for the round-trip converter. .. versionchanged:: 1.2 rr)rY)argsr[rFrFrG TextParser|s8rrbcCstdd|DS)Ncss"|]}|dks|dkrdVqdS)NrUrF)rrrFrFrGrsz#count_empty_vals..)rw)valsrFrFrGcount_empty_valssrc@seZdZeeefdddZddZddZd4d d Z d d Z d5d dZ ddZ ddZ ddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-Zd.d/Zd0d1Zd6d2d3ZdS)7r)rc s.t|d_g_d_d_|d_tjrBj_nfdd_t |d_ |d_ |d_ t j trtj _ |d _|d _|d _|d _|d _t|d\_}|d_|d_|d_|dpd_d_d|kr|d_|d_|d_|d_|d_|d_|d_ t |t!rnt"t#t|_nj$||j%dk st&t'j%j(dst&z)j%j(Wn&t*j+t,fk r-YnXd_.z/\_0_1_2Wn$t3t4fk r-YnXt5j0dkr\6j0j7j8\_0_7_8}t5j0_1n j0d_0t!j0_9j:s;j0\}_9_0d_<j7dkr|_7=j0j>rʈ?_@nd_@t5jdkrt4djdkr tABdjd _CntABdjd!jd _CdS)"zN Workhorse function for processing nested list into DataFrame Nrrkcs |jkSr)rkrrrFrGz'PythonParser.__init__..rlrarcrbrerfrgrdryrrrrNFrrzrqrrrtrvrureadlinerUTz'Only length-1 decimal markers supportedz[^-^0-9^z]+^)DrrrTbufposline_posrkrskipfuncrrlrarcrKrrbrerfrgrdrryrrrZ names_passedrrzrqrrrtrvrurrr r-r)rrr _make_readercsvErrorrr _col_indices_infer_columnsrnum_original_columnsr rrBrIrIr!r"rr8_get_index_namer'r6rR_set_no_thousands_columns_no_thousands_columnsrecompilenonnum)rrr[rWr!rFrrGrs                                zPythonParser.__init__cstfdd}tjtrTjD]*}t|trH|D] }||q8q&||q&ntjtrjD]*}t|tr|D] }||q|qj||qjn<jrtjtrjD] }||qnjdk r|jS)Ncs*t|r|nj|dSr)r$addrrrZnoconvert_columnsrrFrGr= s z4PythonParser._set_no_thousands_columns.._set)rJrKrRrrrrirrFrrGr8 s*              z&PythonParser._set_no_thousands_columnsc s4jdkstdkrjr*tdGfdddtj}|}dk rT|_n}|ggd}j s~|sj d7_ }|ggd}qn|d}j d7_ j d7_ t |}|j|_tj t||d}jt|tj |dd}nfd d } | }|_dS) NrUz.MyDialect N) rrrrarcrbrerfrdrgrFrrFrG MyDialecte srr)rT)rstrictc3s@}t}||VD]}||Vq&dSr)rrrsplitstrip)linepat)rrrFrGr] s  z(PythonParser._make_reader.._read)rarIrgrBrDialectr_check_commentsrrrSniffersniffreaderrrextendrrT) rrrZdiarlinessniffedZline_rdrrr]rF)rrrrGr\ s6  zPythonParser._make_readerNc Csz||}Wn*tk r8|jr*g}n |YnXd|_t|j}t|s||j}t||j |j |j \}}}| ||j }|||fSt|d}d}|jr|t|kr|d}|dd}||} || } ||j}||| \}} || } || | ||\}}||| fS)NFrrU) _get_linesrr(rrrrIrLrrir!rrrNr"rr _rows_to_cols_exclude_implicit_indexrr _convert_datarX) rrowscontentrrNrrZcount_empty_content_valsrVrUrTrFrFrGrZ s>          zPythonParser.readcCsr||j}|jrZ|j}i}d}t|D].\}}|||krF|d7}q0|||||<q(nddt||D}|S)NrrUcSsi|]\}}||qSrFrFrrFrFrGr sz8PythonParser._exclude_implicit_index..)rLrr\rirrF)rrUrNZ excl_indicesrToffsetr rrFrFrGr s   z$PythonParser._exclude_implicit_indexcCs|dkr|j}|j|dS)N)r)rTrZrrFrFrGr szPythonParser.get_chunkc sfdd}|j}tjts*j}n |j}i}i}tjtrjD]F}j|}j|} t|tr|jkrj|}|||<| ||<qNn j}j}|||j ||S)Ncs@i}|D].\}}t|tr2|jkr2j|}|||<q |S)zconverts col numbers to names)rrKrAr)rcleanrrrrFrG_clean_mapping s  z2PythonParser._convert_data.._clean_mapping) rqrKrrrrmrrArrtrz) rrTrZ clean_convZ clean_dtypesZclean_na_valuesZclean_na_fvaluesrZna_valueZ na_fvaluerFrrGr s8          zPythonParser._convert_datac sj}d}d}t}jdk rj}t|tttjfr`t|dk}|rjt||ddg}n d}|g}g}t |D]h\}} z } j | kr } qWnt k rV} zj | krtd| dj dd| |r&| dkr&|r|dgt|d|||fWY*Sjs8td | jdd} W5d} ~ XYnXgg} t | D]V\} }|d kr|rd | d |}n d | }| | |n |qh|s8jr8tt}t D]V\} }||}|dkr|d||<|d |}||}q|| <|d||<qnr|r| |dkrt}jdk rjtjnd}t| }||kr|||krd}dg|jdg_||fdd| Dt|dkrvt}qv|r|dk rjdk rt|tjks<jdkrDt|t|dkrDtdt|dkrZtdjdk rt||nd_t|}|g}n||d}nz } Wn@t k r} z |std | |dd} W5d} ~ XYnXt| }|}|s@jr fddt|Dg}ntt|g}||d}nrjdksZt||krr|g|}t|}n@tjst|tjkrtd|g||g}|}|||fS)NrTrUr;FzPassed header=z but only z lines in filezNo columns to parse from filerz Unnamed: Z_level_r`csh|] }|qSrFrFr) this_columnsrFrGr  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|]}j|qSrFrrrrFrGr sz/PythonParser._infer_columns..)rNrJrhrKrrrrrIr_buffered_liner _next_linerrB _clear_bufferrrr~rrArirrryr_handle_usecolsrrjrr)rrNrZ clear_bufferr rhZhave_mi_columnsrlevelhrrrZthis_unnamed_colsr rrhrJrrKlcrHZ unnamed_countZncolsrF)rrrGr s                          zPythonParser._infer_columnsc s|jdk rt|jr"t|j|ntdd|jDrt|dkrJtdg|jD]P}t|trz| |Wqtk rt |j|YqXqT|qTn|jfdd|D}|_ |S)zb Sets self._col_indices usecols_key is used if there are string usecols. Ncss|]}t|tVqdSrr/)rurFrFrGr sz/PythonParser._handle_usecols..rUz4If using multiple headers, usecols must be integers.cs"g|]}fddt|DqS)csg|]\}}|kr|qSrFrFrZ col_indicesrFrGr sz;PythonParser._handle_usecols...)r)rrrrFrGr sz0PythonParser._handle_usecols..) ryrrr&rIrBrKrrrrr)rrZ usecols_keyrrFrrGr s,      zPythonParser._handle_usecolscCs$t|jdkr|jdS|SdS)zH Return a line from buffer, filling buffer if required. rN)rIrrrrFrFrGr s zPythonParser._buffered_linecCs|s|St|dts|S|ds&|S|dd}|tkr>|S|d}t|dkr|d|jkrd}|d}|dd|d}|||}t||dkr|||dd7}n |dd}|g|ddS)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. rrUrN)rKr_BOMrIrcr)rZ first_rowZ first_eltZ first_row_bomstartquoteendnew_rowrFrFrG_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|] }| VqdSrrFrCrFrFrGr= sz.PythonParser._is_line_empty..)r)rrrFrFrG_is_line_empty0 s zPythonParser._is_line_emptycCst|jtr||jr(|jd7_q zr||j|jgd}|jd7_|jsv||j|jdsp|rvWqn"|jr||g}|r|d}WqWq(t k rt Yq(Xq(n||jr|jd7_|jdk st t |jq|j |jdd}|jd7_|dk r||gd}|jrL||g}|r`|d}qbq||sb|rqbq|jdkrx||}|jd7_|j||S)NrUrrow_num)rKrTrrrrrr_remove_empty_lines IndexErrorrrr_next_iter_linerrrr)rrretZ orig_linerFrFrGr? sN         zPythonParser._next_linecCs:|jrt|n&|jr6d|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 z: rN)rrrrstderrwrite)rrErbaserFrFrG_alert_malformedu s   zPythonParser._alert_malformedc Csz|jdk stt|jWStjk r}zX|js:|jr|t|}d|ksRd|krVd}|jdkrpd}|d|7}| ||WYdSd}~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. Nz 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).. ) rTrrrrrrrrlr)rrerEreasonrFrFrGr s      zPythonParser._next_iter_linecCs|jdkr|Sg}|D]j}g}|D]R}t|tr:|j|krF||q"|d||j}t|dkrp||qvq"||q|Sr7)rurKrrfindrI)rrrrrlrDrFrFrGr s     zPythonParser._check_commentscCsNg}|D]@}t|dks>t|dkrt|dtr>|dr||q|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. rUr)rIrKrrr)rrrrrFrFrGr s     z PythonParser._remove_empty_linescCs |jdkr|S|j||jddS)Nrrsearchreplace)rt_search_replace_num_columnsrrrFrFrG_check_thousands s zPythonParser._check_thousandsc Csg}|D]t}g}t|D]X\}}t|trR||ksR|jrB||jksR|j|r^||q||||q||q|Sr) rrKrrrrrrr) rrrrrrrr rDrFrFrGr s$  z(PythonParser._search_replace_num_columnscCs$|jtdkr|S|j||jddS)Nrvr`r)rvrrrrFrFrG_check_decimal szPythonParser._check_decimalcCs g|_dSr)rrrFrFrGr szPythonParser._clear_bufferFc CsHt|}t|}z |}Wntk r4d}YnXz |}Wntk rZd}YnXd}|dk r|jdk rt||j}|dk rt|t||jkrttt||_|jdd|_t|D]}| d|qt|}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. NrFrUT) rrrrirIrrrreversedinsertr\rEr ) rrrrZ next_lineZimplicit_first_colsrZ index_nameZcolumns_rFrFrGr sD            zPythonParser._get_index_namecsj}jr|tj7}tdd|D}||krDjdk rDjdkrDjrZjnd}g}t|}t|}g}|D]Z\}} t| } | |krʈjsj rԈj |||} | | | fjrqqz| | qz|D]h\} } d|d| dd| } j r2tj dkr2j tjkr2d } | d | 7} | | dqttj||d j}jrjrfd d t|D}nfdd t|D}|S)Ncss|]}t|VqdSr)rIrrowrFrFrGrI sz-PythonParser._rows_to_cols..Frz Expected z fields in line rUz, saw zXError could possibly be due to quotes being ignored when a multi-char delimiter is used.r)Z min_widthcs6g|].\}}|tjks.|tjjkr|qSrF)rIrirrr arrFrGr| s  z.PythonParser._rows_to_cols..csg|]\}}|jkr|qSrF)rrrrFrGr s )rr\rIrimaxryrlrrrrrrardr QUOTE_NONErrrZto_object_arrayT)rrZcol_lenmax_lenZfootersZ bad_lines iter_contentZ content_lenr lZ actual_lenrrErZzipped_contentrFrrGrC sT"         zPythonParser._rows_to_colscs*j}d}|dk rPtj|krBjd|j|d}_n|tj8}|dkrtjtrjtjkrzt|dkrjjd}tj}n jjj|}j|}jrڇfddt|D}| ||_ng}z|dk r8t |D]&}jdk st | t jq| |n:d}jj|dd}|d7}|dk r<| |q.rrUrcs$g|]\}}|js|qSrFr r rrFrGr s)rrIrKrTrrrrkrrrrrrrrlrrrrr)rrrrnew_posrWrrFrrGr sf"               zPythonParser._get_lines)N)N)N)rrrrrr rrrrZrrrrrrrrrrrrrrrrrr\rrrrFrFrFrGrs4{$C , ;4" 36)@Nrcsfdd}|S)Nc sdkrbt|}z tjt|dddWStk r^tjtj|ddYSXnz.tj|dd}t|t j rt d|WSt k rz&tjtjt|dddWYSt k rt f|YYSXYnXdS) Nignore)utcrxerrorsrcache)rx)r)rrz scalar parser)r\rx)r) rZconcat_date_colstools to_datetimerZto_numpyrBrPrKdatetimerr;) date_colsstrsrrsrQrxrrFrG converter sJ     z'_make_date_converter..converterrF)rQrxrrsrrFrrGr# s'r#csfdd}g}i} |} t|}t} |dks:t|trB||fSt|tr|D]} t| rt| trv| |krv| | } || rqP||| || <qPt|| || \} }}| |krtd| || | <|| | |qPnht|t rD| D]R\} } | |krtd| dt|| || \}}}|| | <|| | |q| | | ||st| D]}| |||qf||fS)Ncs$ttr|kp"tto"|kSr)rKr)colspecrir!rFrG_isindex sz*_process_date_conversion.._isindexz New date column already in dict z Date column z already in dict)rrJrKrXr(rA_try_convert_datesrBrrrrrrra) data_dictrZ parse_specrir!rrwrZnew_colsZnew_datarrrnew_namerZ old_namesrWrrFrrGr s^             rc st|}g}|D]D}||kr(||qt|trJ||krJ|||q||qddd|D}fdd|D}||} || |fS)NrWcss|]}t|VqdSrrBrCrFrFrGra sz%_try_convert_dates..csg|]}|kr|qSrFrFrrrFrGrb sz&_try_convert_dates..)rJrrKrAr4) r\rrrcolsetcolnamesrrZto_parseZnew_colrFrrGrU s  rcCs|dkr |rt}nt}t}nt|tr|}i}|D].\}}t|sT|g}|rdt|tB}|||<q>dd|D}n*t|s|g}t|}|r|tB}t|}||fS)NcSsi|]\}}|t|qSrF)_floatify_na_valuesrrFrFrGr sz$_clean_na_values..) rrJrKrrrr&_stringify_na_valuesr!)rmrnrZ old_na_valuesrrrFrFrGrh s0   rc Cst|sd||fSt|}t|}g}t|}t|D]j\}}t|tr||t|D]&\}}||krZ|||<||qqZq6||}||||q6t|D]"\}}t|tr||krd||<q|||fSr)rrrrKrrra) rrir Zcp_colsr!r rr9rCrFrFrGrE s*       rEc st|}tts,pttfddnB}tdd|D]$\}}t|r`||n|}||<qH|dks|dks|dkrtg}nFfdd|D} t | |d}| t |D]\} } | | | qfdd |D} ||| fS) NcsSrrFrF) default_dtyperFrGr rz!_get_empty_meta..cSstSr)objectrFrFrFrGr rFcsg|]}tg|dqSr|r5)rrCr|rFrGr sz#_get_empty_meta..rMcsi|]}|tg|dqSr%r5)rrhr|rFrGr sz#_get_empty_meta..) rrKrr$rrrr$r1r4rrr) rrir!rrZ_dtyperrrrrTr rArrF)r#rrrGr s$     rc CsPt}|D]@}z t|}t|s,||Wq tttfk rHYq Xq |Sr)rJfloatrisnanrrrB OverflowError)rmrrrFrFrGr! s r!c Csg}|D]}|t|||zHt|}|t|kr`t|}||d|t|||Wntttfk rYnXz|t|Wqtttfk rYqXqt|S)z3 return a stringified and numeric for these values z.0)rrr&rArrBr(rJ)rmrrDrrFrFrGr" s$  r"cCsJt|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)rKrrrJ)rrmrrnrFrFrGrcs  rccCsFt|}g}|D]0}||kr(||qt|tr|||q|Sr)rJrrKrA)rrrr rrFrFrG_get_col_names1s  r)c@s6eZdZdZd ddZd ddZddd Zd d ZdS)FixedWidthReaderz( A reader of fixed-width lines. NrcCs||_d|_|rd|nd|_||_|dkr>|j||d|_n||_t|jttfsht dt |j |jD]Z}t|ttfrt |dkrt|dt tjt dfrt|dt tjt dfsnt d qndS) Nz z r_)rrkz;column specifications must be a list or tuple, input was a rrrUzEEach column specification must be 2 element tuple or list of integers)rbufferrarudetect_colspecsrrKrrrrrrIrArr)rrrrarurkrrrFrFrGrAs4    zFixedWidthReader.__init__cCsd|dkrt}g}g}t|jD]4\}}||kr:||||t||kr qVq t||_|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)rJrrrrIrr+)rrrkZ buffer_rowsZ detect_rowsr rrFrFrGget_rows_s    zFixedWidthReader.get_rowsc sdddjD}td|d}||}|s@tdttt|}t j |dt d}j dk r|fd d |D}|D](}| |D]} d|| | <qqt |d} d | d <t || Adkd } tt| ddd | ddd } | S) Nrcss|]}d|VqdS)\NrFrCrFrFrGrsz3FixedWidthReader.detect_colspecs..z([^z]+)z(No rows from which to infer column widthrUr|csg|]}|jdqS)r) partitionrurrrFrGrsz4FixedWidthReader.detect_colspecs..rr)r4rarrr-rrr%rIrzerosrArufinditerrrZrollwhererrF) rrrk delimiterspatternrrrrrmZshiftededgesZ edge_pairsrFrrGr,s"   "z FixedWidthReader.detect_colspecscs`jdk r@ztjWqJtk r<d_tjYqJXn tjfddjDS)Ncs$g|]\}}||jqSrF)rra)rZfrommtorrrFrGrsz-FixedWidthReader.__next__..)r+rrrrrrFr8rGrs  zFixedWidthReader.__next__)Nr)N)rN)rrrrrr-r,rrFrFrFrGr*<s   & r*c@s.eZdZdZddZddZedddZd S) rzl Specialization that Converts fixed-width fields into DataFrames. See PythonParser for details. cKs,|d|_|d|_tj||f|dS)Nrr)rrrrr)rrr[rFrFrGrs  zFixedWidthFieldParser.__init__cCs"t||j|j|j|j|j|_dSr)r*rrarurkrrT)rrrFrFrGrsz"FixedWidthFieldParser._make_readerrbcCsdd|DS)z Returns the list of lines without the empty ones. With fixed-width fields, empty lines become arrays of empty strings. See PythonParser._remove_empty_lines. cSs"g|]}tdd|Dr|qS)css"|]}t|t p|VqdSr)rKrr)rrrFrFrGrszGFixedWidthFieldParser._remove_empty_lines...)r&)rrrFrFrGrsz=FixedWidthFieldParser._remove_empty_lines..rFrrFrFrGrsz)FixedWidthFieldParser._remove_empty_linesN)rrrrrrr rrFrFrFrGrs r)rrarrrrcCs|d}i}|dk r2|dko,|tjkp,||k|d<|dkr>|}|rT|tjk rTtd|tjkrh||d<n||d<|dk rd|d<nd|d<d |d<|S) arValidate/refine default values of input parameters of read_csv, read_table. Parameters ---------- dialect : str or csv.Dialect 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. delimiter : str or object Alias for sep. delim_whitespace : bool 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. engine : {{'c', 'python'}} Parser engine to use. The C engine is faster while the python engine is currently more feature-complete. sep : str or object A delimiter provided by the user (str) or a sentinel value, i.e. pandas._libs.lib.no_default. defaults: dict Default values of input parameters. Returns ------- kwds : dict Input parameters with correct values. Raises ------ ValueError : If a delimiter was specified with ``sep`` (or ``delimiter``) and ``delim_whitespace=True``. raN sep_overridezXSpecified a delimiter with both sep and delim_whitespace=True; you can only specify one.TrrrF)r no_defaultrB)rrarrrrZ delim_defaultr[rFrFrGrs(-    r)r[r+cCs<|ddkrdS|d}|tkr0t|}t||S)za Extract concrete csv dialect instance. Returns ------- csv.Dialect or None rN)rWr list_dialects get_dialect_validate_dialect)r[rrFrFrGr#s  r)rarerbrfrcrd)rr+cCs(tD]}t||std|dqdS)zx Validate csv dialect instance. Raises ------ ValueError If incorrect dialect is provided. zInvalid dialect z providedN)MANDATORY_DIALECT_ATTRSrrB)rparamrFrFrGr=As  r=)rrr+c Cs|}tD]}t||}t|}|||}g}||krx||krxd|d|d|d}|dkrn|ddsx|||rtjd |t d d |||<q |S) a Merge default kwargs in TextFileReader with dialect parameters. Parameters ---------- dialect : csv.Dialect Concrete csv dialect. See csv.Dialect documentation for more details. defaults : dict Keyword arguments passed to TextFileReader. Returns ------- kwds : dict Updated keyword arguments, merged with dialect parameters. zConflicting values for 'z': 'z+' was provided, but the dialect specifies 'z%'. Using the dialect-specified value.rar9Fz rr) rr>getattrrrWrrrrr4r) rrr[r?Z dialect_valrprovidedZ conflict_msgsrErFrFrGrOs     rcCs<|dr8|ds|dr&td|dr8tddS)a Check whether skipfooter is compatible with other kwargs in TextFileReader. Parameters ---------- kwds : dict Keyword arguments passed to TextFileReader. Raises ------ ValueError If skipfooter is not compatible with other parameters. rlrSrTz('skipfooter' not supported for iterationrVz''skipfooter' not supported with 'nrows'N)rWrB)r[rFrFrGrs   r)r)r_Nr)N)NFFT)F)T)N)r collectionsrrrriorr1rrtextwraprtypingrrrr r r r r rrrnumpyrZpandas._libs.libZ_libsrZpandas._libs.opsopsr{Zpandas._libs.parsersrzrZpandas._libs.tslibsrZpandas._typingrrrZ pandas.errorsrrrrZpandas.util._decoratorsrZpandas.core.dtypes.castrZpandas.core.dtypes.commonrrrrrr r!r"r#r$r%r&r'r(r)r*Zpandas.core.dtypes.dtypesr+Zpandas.core.dtypes.missingr,Z pandas.corer-r.Zpandas.core.arraysr/Zpandas.core.framer0Zpandas.core.indexes.apir1r2r3r4Zpandas.core.seriesr6Zpandas.core.toolsr7rZpandas.io.commonr8r9r:Zpandas.io.date_convertersr;rr4r5Z_doc_read_csv_and_tablerHrOr] QUOTE_MINIMALrrrrrrr__annotations__rJrformatZ _shared_docsr:rrrrYrrXrAr rrrrrrrrrrr#rrrrErr!r"rcr)r*rrr$rrr>r=rrrFrFrFrGs<  0     H       tu6 ,  (H (I QB  2IB<0 4 E ,$ , # j%    Y   4