3
qd             1   @   s
  U d Z ddlmZmZ ddlZddlZddlmZmZ ddl	Z	ddl
Z
ddlZddlmZ ddlmZmZmZmZmZmZmZ ddlZddlZddljjZddljjZddljj Z ddlm!Z! ddl"m#Z# dd	l$m%Z%m&Z& dd
l'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlImJZJ ddlKmLZLmMZMmNZNmOZO ddlPmQZQ ddlRmSZT ddlUmVZVmWZWmXZXmYZY ddlZm[Z[ dZ\dedj]e^e!ddd d Z_dsdd Z`d!d" Zae%d#d$d%Zbddd&ejcd'd(dd)dddddddd'ddddd'ddd*d(d(d(dddd(dd(dd'd(d'd+%Zdd(d'd'd(d'd'dd,Zed)d-dd.Zfd/hZgd0d1hZhi Zieejef iek Zleej le-e_jmd2d3d4d5d6dd)dddd(dd'dddddd(ddddd'd'd(d'd(d(d(dd(d'd(dd)dd*dd&ejcd'ddddd'd'd(eed0 d(df0e%ejd7d8d2Zne-e_jmd9d:d;d5d<dd)dddd(dd'dddddd(ddddd'd'd(d'd(d(d(dd(d'd(dd)dd*dd&ejcd'ddddd'd'd(eed0 d(df0e%ejd7d=d9Zodte%d#d>d?ZpG d@dA dAejqZrdBdC Zsduee&eteeu f  dDdEdFZvdGdH ZwdIdJ ZxdKdL ZydMdN ZzdOdP Z{G dQdR dRZ|G dSdT dTe|Z}dUdV Z~dWdX ZG dYdZ dZe|Zdvd[d\Zdwd]d^Zd_d` ZdxdadbZdcdd ZdydedfZdgdh Zdidj Zdkdl Zdmdn ZG dodp dpejqZG dqdr dreZdS )zzM
Module contains tools for processing files into DataFrames or other objects
    )abcdefaultdictN)StringIOTextIOWrapper)fill)AnyDictIterableListOptionalSequenceSet)STR_NA_VALUES)parsing)FilePathOrBufferUnion)AbstractMethodErrorEmptyDataErrorParserErrorParserWarning)Appender)astype_nansafe)ensure_object
ensure_stris_bool_dtypeis_categorical_dtypeis_dict_likeis_dtype_equalis_extension_array_dtypeis_file_likeis_float
is_integeris_integer_dtypeis_list_likeis_object_dtype	is_scalaris_string_dtypepandas_dtype)CategoricalDtype)isna)
algorithms)Categorical)	DataFrame)Index
MultiIndex
RangeIndexensure_index_from_sequences)Series)	datetimes)get_filepath_or_buffer
get_handleinfer_compressionvalidate_header_arg)generic_parseru   ﻿a  
{summary}

Also supports optionally iterating or breaking of the file
into chunks.

Additional help can be found in the online docs for
`IO Tools <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.

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 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 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', 'F   z    )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 : 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()``.
chunksize : int, optional
    Return TextFileReader object for iteration.
    See the `IO Tools docs
    <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_
    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.
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
    <https://docs.python.org/3/library/codecs.html#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.
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
--------
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
c             C   s^   d| dd|d}|dk	rZt |rBt||kr8t|t|}nt|oP||ksZt||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!   )namevalZmin_valmsg rB   3/tmp/pip-build-7vycvbft/pandas/pandas/io/parsers.py_validate_integerq  s    
rD   c             C   sH   | dk	rDt | t t| kr$tdt| ddp:t| tjsDtddS )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.)lensetr>   r#   
isinstancer   KeysView)namesrB   rB   rC   _validate_names  s
    rJ   )filepath_or_bufferc             C   s"  |j dd}|dk	r.tjdd|j }||d< |j dd}t| |}t| ||\}}}}||d< |j dddk	rt|d trd	|d< |j d
d}td|j ddd}|j dd}	t	|j dd t
|f|}
|s|r|
S z|
j|	}W d|
j  X |ry|j  W n tk
r   Y nX |S )zGeneric reader of line files.encodingN_-compressioninferdate_parserparse_datesTiteratorF	chunksize   nrowsrI   )getresublowerr5   r3   rG   boolrD   rJ   TextFileReaderreadcloser>   )rK   kwdsrL   rO   Z	fp_or_bufrM   Zshould_closerS   rT   rV   parserdatarB   rB   rC   _read  s8    

rb   "TFrP   .)%	delimiter
escapechar	quotecharquotingdoublequoteskipinitialspacelineterminatorheader	index_colrI   prefixskiprows
skipfooterrV   	na_valueskeep_default_natrue_valuesfalse_values
convertersdtypecache_dates	thousandscommentdecimalrR   keep_date_coldayfirstrQ   usecolsrT   verboserL   squeezerO   mangle_dupe_colsinfer_datetime_formatskip_blank_lines)delim_whitespace	na_filter
low_memory
memory_maperror_bad_lineswarn_bad_linesfloat_precisiond   )colspecsinfer_nrowswidthsrp   r   r   read_csvz8Read a comma-separated values (csv) file into DataFrame.z',')	func_namesummaryZ_default_sep,)rK   rz   c1       5   2   C   s   d}1|*d k	r(|d ko||1k}2t |2d}3nt  }3|d kr:|}|-rN||1krNtd|d k	r\d}4nd}d}4|3j|||*| |4|&|'|$|%||#|||||||||||!|(|"||||||||||
|||)||/|0||-|,|+|.|	||d0 t| |3S )Nr   )sep_overridezXSpecified a delimiter with both sep and delim_whitespace=True; you can only specify one.TcF)0re   enginedialectrO   engine_specifiedri   rf   rg   rh   rj   rk   rl   rm   rI   rn   ro   rp   rq   rs   rt   rr   rx   ry   rz   rR   r{   r|   rQ   rw   rV   rS   rT   ru   rv   r}   r~   rL   r   r   r   r   r   r   r   r   r   r   r   )dictr>   updaterb   )5rK   sepre   rl   rI   rm   r}   r   rn   r   rv   r   ru   rs   rt   rj   ro   rp   rV   rq   rr   r   r~   r   rR   r   r{   rQ   r|   rw   rS   rT   rO   rx   rz   rk   rg   rh   ri   rf   ry   rL   r   r   r   r   r   r   r   Zdefault_sepr   r_   r   rB   rB   rC   r     s    N
read_tablez+Read general delimited file into DataFrame.z'\\t' (tab-stop)	c1       1      C   s0   |-r|d k	s|dkrt d|-r$d}tf t S )Nr   zXSpecified a delimiter with both sep and delim_whitespace=True; you can only specify one.r   )r>   r   locals)1rK   r   re   rl   rI   rm   r}   r   rn   r   rv   r   ru   rs   rt   rj   ro   rp   rV   rq   rr   r   r~   r   rR   r   r{   rQ   r|   rw   rS   rT   rO   rx   rz   rk   rg   rh   ri   rf   ry   rL   r   r   r   r   r   r   r   rB   rB   rC   r     s    Cc             K   s   |dkr|dkrt dn|d
kr2|dk	r2t d|dk	rlg d }}x&|D ]}|j||| f ||7 }qJW ||d< ||d< d|d	< t| |S )aX  
    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
    <https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html>`_.

    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
    --------
    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 widthsrP   z4You must specify only one of 'widths' and 'colspecs'r   r   r   z
python-fwfr   )NrP   )r>   appendrb   )rK   r   r   r   r_   colwrB   rB   rC   read_fwf  s    ?


r   c               @   sp   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dddZ
dd ZdddZdd ZdddZdS )r\   zF

    Passed dialect overrides any of the related parser options

    Nc             K   s:  || _ |d k	rd}nd}d}|jd|| _|jdd k	r6|d }|tj krXtj|}xd"D ]}yt||}W n8 tk
r } ztd|d  d|W Y d d }~X nX t	| }	|j||	}
g }|
|	ko|
|krd| d|
 d| d}|dko |j
dds|j| |r*tjdj|tdd |||< q^W |jdrv|jdsZ|jdrbtd|jdrvtd|jdddkr|jdd krdnd |d< || _|| _d | _d| _| j|}|j
dd | _|j
dd | _|j
d d| _| j||| _| j||\| _| _d!|kr*|d! | jd!< | j| j d S )#NTpythonFr   r   re   ri   rf   rj   rg   rh   zInvalid dialect z	 providedzConflicting values for 'z': 'z+' was provided, but the dialect specifies 'z%'. Using the dialect-specified value.r   z

   )
stacklevelrp   rS   rT   z*'skipfooter' not supported for 'iteration'rV   z''skipfooter' not supported with 'nrows'rl   rP   rI   r   r   has_index_names)re   ri   rf   rj   rg   rh   )frW   _engine_specifiedcsvlist_dialectsget_dialectgetattrAttributeErrorr>   _parser_defaultspopr   warningswarnjoinr   orig_optionsr   _engine_currow_get_options_with_defaultsrT   rV   r   _check_file_or_buffer_clean_optionsoptions_make_engine)selfr   r   r_   r   r   paramZdialect_valerrparser_defaultprovidedZconflict_msgsrA   r   rB   rB   rC   __init__Z  sl    
     


zTextFileReader.__init__c             C   s   | j j  d S )N)r   r^   )r   rB   rB   rC   r^     s    zTextFileReader.closec             C   s  | j }i }x@tj D ]4\}}|j||}|dkr@| r@tdq|||< qW xtj D ]\}}||kr|| }|dkr||krd|kr|tkrq|tj||krqtdt| dt| dntj||}|||< qVW |dkr
x$t	j D ]\}}|j||||< qW |S )	Nr   z3Setting mangle_dupe_cols=False is not supported yetr   r   zThe z" option is not supported with the z enginez
python-fwf)
r   r   itemsrW   r>   _c_parser_defaults_python_unsupported_deprecated_defaultsrepr_fwf_defaults)r   r   r_   r   ZargnamedefaultvaluerB   rB   rC   r     s.    

z)TextFileReader._get_options_with_defaultsc             C   s0   t |r,d}|dkr,t|| r,d}t||S )N__next__r   z<The 'python' engine cannot iterate through this file buffer.)r   hasattrr>   )r   r   r   Z	next_attrrA   rB   rB   rC   r     s    z$TextFileReader._check_file_or_bufferc             C   s  |j  }| j}d }|d }|d }|dkr>|d dkr>d}d}tj pHd}|d krj| rj|dkrhd	}d}n|d k	rt|d
kr|dkr|dkrd|d< |d= n|d*krd}d}n||rd|krd|d< nf|d k	r,d}	yt|j|d
krd}	W n tk
r   d}	Y nX |	 r,|d+kr,d| d}d}|d }
|
d k	r|t|
tt	fr|t|
d
kr|t
|
dkr||d,kr|d}d}|r|rt||dkrxtD ]}||= qW d|krxFtD ]>}|r|| t| krtd| dt| d||= qW |r tjd| dtdd |d }|d }|d }|d }|d }t|d   d!}xVtD ]N}t| }t| }d"t| d#}|j|||kr||d$ 7 }n|||< q^W |d!krtj|td%d |dkrtd&t|r t|tttjfs |g}||d< |d k	rt|n|}|d k	rJt|tsNtd't|j  ni }|d( }t!||\}}|dkrt"|rtt#|}|d krt$ }nt%|st$|}||d< ||d< ||d< ||d)< ||d< ||fS )-Nre   r   r   rp   r   z*the 'c' engine does not support skipfooterr   zutf-8zDthe 'c' engine does not support sep=None with delim_whitespace=FalserU   z\s+T
python-fwfzxthe 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)Fzthe separator encoded in zF is > 1 char long, and the 'c' engine does not support such separatorsrg      zxord(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'.   )r   rm   rI   ru   rq   ro   rl    zThe zF argument has been deprecated and will be removed in a future version.z

r   z)The value of index_col couldn't be 'True'z8Type converters must be a dict or subclass, input was a rr   
na_fvalues)r   r   )r   r   )r   r   )&copyr   sysgetfilesystemencodingrE   encodeUnicodeDecodeErrorrG   strbytesordr>   _c_unsupportedr   r   r   r   r   r   r6   _deprecated_argsr   rW   FutureWarning_is_index_collisttuplenpndarrayr   	TypeErrortype__name___clean_na_valuesr!   rangerF   callable)r   r   r   resultr   Zfallback_reasonr   r   rL   Z
encodeablerg   argrm   rI   ru   rq   ro   Zdepr_warningr   Zdepr_defaultrA   rr   r   rB   rB   rC   r     s    

















zTextFileReader._clean_optionsc             C   s,   y| j  S  tk
r&   | j   Y nX d S )N)	get_chunkStopIterationr^   )r   rB   rB   rC   r     s
    zTextFileReader.__next__r   c             C   s^   |dkrt | jf| j| _n>|dkr*t}n|dkr8t}ntd| d|| jf| j| _d S )Nr   r   z
python-fwfzUnknown engine: z3 (valid options are "c", "python", or "python-fwf"))CParserWrapperr   r   r   PythonParserFixedWidthFieldParserr>   )r   r   klassrB   rB   rC   r     s    zTextFileReader._make_enginec             C   s   t | d S )N)r   )r   rB   rB   rC   _failover_to_python  s    z"TextFileReader._failover_to_pythonc             C   s   t d|}| jj|}| j|\}}}|d kr`|rZttt|j }t| j	| j	| }qhd}nt|}t
|||d}|  j	|7  _	| jrt|jdkr||jd  j S |S )NrV   r   )columnsindexrU   )rD   r   r]   _create_indexrE   nextitervaluesr/   r   r,   r   r   r   )r   rV   retr   r   col_dictnew_rowsZdfrB   rB   rC   r]     s    
zTextFileReader.readc             C   s   |\}}}|||fS )NrB   )r   r   r   r   r   rB   rB   rC   r     s    
zTextFileReader._create_indexc             C   sF   |d kr| j }| jd k	r:| j| jkr(tt|| j| j }| j|dS )N)rV   )rT   rV   r   r   minr]   )r   sizerB   rB   rC   r     s    
zTextFileReader.get_chunk)N)r   )N)N)r   
__module____qualname____doc__r   r^   r   r   r   r   r   r   r]   r   r   rB   rB   rB   rC   r\   S  s   
\& %

r\   c             C   s   | d k	o| dk	S )NFrB   )r   rB   rB   rC   r     s    r   )rm   c                s@    dkst  trg  t| o>t | t o>t fdd| D S )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
    Nc             3   s$   | ]}|t  krt|tV  qd S )N)r   rG   r   ).0r   )rm   rB   rC   	<genexpr>  s    z,_is_potential_multi_index.<locals>.<genexpr>)rG   r[   rE   r.   all)r   rm   rB   )rm   rC   _is_potential_multi_index  s
    r   c                s"   t  r fddt|D S  S )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'.
    c                s   h | ]\}} |r|qS rB   rB   )r   ir?   )r}   rB   rC   	<setcomp>  s    z$_evaluate_usecols.<locals>.<setcomp>)r   	enumerate)r}   rI   rB   )r}   rC   _evaluate_usecols  s    r  c                s0    fdd| D }t |dkr,t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.
    c                s   g | ]}| kr|qS rB   rB   )r   r   )rI   rB   rC   
<listcomp>  s    z+_validate_usecols_names.<locals>.<listcomp>r   z>Usecols do not match columns, columns expected but not found: )rE   r>   )r}   rI   missingrB   )rI   rC   _validate_usecols_names   s
    r  c             C   s$   t | std| dk r td| 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.
    zskipfooter must be an integerr   zskipfooter cannot be negative)r!   r>   )rp   rB   rB   rC   _validate_skipfooter_arg  s
    r  c             C   sb   d}| dk	rZt | r| dfS t| s,t|tj| dd}|dkrJt|t| } | |fS | dfS )	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emptyintegerstring)r  r	  r
  )r   r#   r>   libZinfer_dtyperF   )r}   rA   usecols_dtyperB   rB   rC   _validate_usecols_arg=  s    r  c             C   sB   d}| dk	r>t | r(tj| s>t|nt| ttfs>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%   r  Zis_boolr   rG   r   r   )rR   rA   rB   rB   rC   _validate_parse_dates_argo  s    

r  c               @   s   e Zd Zdd Zee ddddZdd Zed	d
 Z	dd Z
d%ddZdd Zd&ddZd'ddZdZdd Zdd Zd(ddZd)ddZd*dd Zd!d" Zd#d$ ZdS )+
ParserBasec             C   s@  |j d| _d | _|jdd | _|j dd | _t | _d | _d | _	t
|jdd| _|jdd | _|jdd| _|jdd| _|j d	| _|j d
| _|j dd| _|j dd| _|j d| _|j d| _|j dd| _|jdd| _|jdd| _t| j| j| j| jd| _|j d| _t| jtttjfrt t!t"| jsJt#dt$dd | jD rht#d|j dr|t#d|j drt#d| jd k	r*t| jtttjf}|rt t!t"| jpt"| js*t#dnL| jd k	r*| jd k	r t#dn*t"| jst#dn| jdk r*t#dd| _%d| _&g | _'d S ) NrI   rn   rm   rR   FrQ   r|   r{   rq   r   r   rr   Trs   rt   r   r   rw   )rQ   r|   r   rw   rl   z*header must be integer or list of integersc             s   s   | ]}|d k V  qdS )r   NrB   )r   r   rB   rB   rC   r     s    z&ParserBase.__init__.<locals>.<genexpr>z8cannot specify multi-index header with negative integersr}   z;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 Noner   zUPassing negative integer to header is invalid. For no header, use header=None instead)(rW   rI   
orig_namesr   rn   rm   rF   unnamed_colsindex_names	col_namesr  rR   rQ   r|   r{   rq   r   r   rr   rs   rt   r   r   rw   _make_date_converter
_date_convrl   rG   r   r   r   r   r   mapr!   r>   any_name_processed_first_chunkhandles)r   r_   Zis_sequencerB   rB   rC   r     sr    
zParserBase.__init__N)r   returnc                sx   t | jrtj| jj  }n(t| jr@tjjdd | jD }ng }djt fdd|D }|rtt	d| ddS )	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.

        c             s   s    | ]}t |r|n|gV  qd S )N)r#   )r   r   rB   rB   rC   r     s    z<ParserBase._validate_parse_dates_presence.<locals>.<genexpr>z, c                s"   h | ]}t |tr| kr|qS rB   )rG   r   )r   r   )r   rB   rC   r     s   z<ParserBase._validate_parse_dates_presence.<locals>.<setcomp>z+Missing column provided to 'parse_dates': 'r:   N)
r   rR   	itertoolschainr   r#   from_iterabler   sortedr>   )r   r   Zcols_neededZmissing_colsrB   )r   rC   _validate_parse_dates_presence  s    


z)ParserBase._validate_parse_dates_presencec             C   s   x| j D ]}|j  qW d S )N)r  r^   )r   r   rB   rB   rC   r^     s    zParserBase.closec             C   s6   t | jtp4t | jto4t| jdko4t | jd tS )Nr   )rG   rR   r   r   rE   )r   rB   rB   rC   _has_complex_date_col  s    z ParserBase._has_complex_date_colc             C   s|   t | jtr| jS | jd k	r(| j| }nd }| j| }t| jr\|| jkpZ|d k	oZ|| jkS || jkpv|d k	ov|| jkS d S )N)rG   rR   r[   r  rm   r%   )r   r   r?   jrB   rB   rC   _should_parse_dates  s    




zParserBase._should_parse_datesFc       	         s>  t |dk r|d |||fS j}|dkr.g }t|tttjfsF|g}t||jd}t	|jj
\}}}t |d fdd tt fdd|D  }|| }xVtt |d D ]Btfd	d|D rd
jdd jD }td| dqW t |r fdd|D }ndgt | }d}||||fS )z
        extract and return the names, index_names, col_names
        header is a list-of-lists returned from the parsers
        r   r   NrU   c                s   t  fddtD S )Nc             3   s   | ]}|kr | V  qd S )NrB   )r   r   )rsicrB   rC   r   K  s    zMParserBase._extract_multi_indexer_columns.<locals>.extract.<locals>.<genexpr>)r   r   )r$  )field_countr%  )r$  rC   extractJ  s    z:ParserBase._extract_multi_indexer_columns.<locals>.extractc             3   s   | ]} |V  qd S )NrB   )r   r$  )r'  rB   rC   r   M  s    z<ParserBase._extract_multi_indexer_columns.<locals>.<genexpr>c             3   s    | ]}t |  jkV  qd S )N)r   r  )r   r   )nr   rB   rC   r   S  s    r   c             s   s   | ]}t |V  qd S )N)r   )r   xrB   rB   rC   r   T  s    zPassed header=[z3] are too many rows for this multi_index of columnsc                s2   g | ]*}|d  dk	r*|d   j kr*|d  ndqS )r   N)r  )r   r$  )r   rB   rC   r  ]  s   z=ParserBase._extract_multi_indexer_columns.<locals>.<listcomp>T)rE   rm   rG   r   r   r   r   rF   r   _clean_index_namesr  zipr   r   r   rl   r   )	r   rl   r  r  passed_namesicrI   rm   r   rB   )r'  r&  r(  r   r%  rC   _extract_multi_indexer_columns,  s4    



z)ParserBase._extract_multi_indexer_columnsc             C   s   | j rt|}tt}t|| j}xt|D ]z\}}|| }xT|dkr|d ||< |rx|d d |d  d| f }n| d| }|| }q>W |||< |d ||< q,W |S )Nr   rU   rd   r*  r*  )r   r   r   r=   r   rm   r  )r   rI   countsZis_potential_mir   r   	cur_countrB   rB   rC   _maybe_dedup_namesg  s    
"zParserBase._maybe_dedup_namesc             C   s   t |rtj||d}|S )N)rI   )r   r.   from_tuples)r   r   r  rB   rB   rC   _maybe_make_multi_index_columns  s    z*ParserBase._maybe_make_multi_index_columnsc             C   s   t | j s| j rd }nh| js8| j||}| j|}nJ| jr| jshtt|| j| j\| _	}| _d| _| j
||}| j|dd}|rt|t| }|j|d | }| j|| j}||fS )NTF)try_parse_dates)r   rm   r!  _get_simple_index
_agg_indexr  r+  r   r  r  _get_complex_date_indexrE   Z	set_namesr4  r  )r   ra   alldatar   indexnamerowr   rM   ZcoffsetrB   rB   rC   _make_index  s"    zParserBase._make_indexc             C   st   dd }g }g }x.| j D ]$}||}|j| |j||  qW x.t|ddD ]}|j| | jsN|j| qNW |S )Nc             S   s"   t | ts| S td|  dd S )NzIndex z invalid)rG   r   r>   )r   rB   rB   rC   ix  s    
z(ParserBase._get_simple_index.<locals>.ixT)reverse)rm   r   r  r   _implicit_index)r   ra   r   r<  	to_remover   idxr   rB   rB   rC   r6    s    

zParserBase._get_simple_indexc       	         sr    fdd}g }g }x.| j D ]$}||}|j| |j||  qW x(t|ddD ]}|j|  j| qRW |S )Nc                sL   t | tr| S  d kr&td| dx t D ]\}}|| kr0|S q0W d S )Nz Must supply column order to use z	 as index)rG   r   r>   r  )Zicolr   r   )r  rB   rC   	_get_name  s    
z5ParserBase._get_complex_date_index.<locals>._get_nameT)r=  )rm   r   r  r   remove)	r   ra   r  rA  r?  r   r@  r?   r   rB   )r  rC   r8    s    

z"ParserBase._get_complex_date_indexTc             C   s   g }xt |D ]\}}|r.| j|r.| j|}| jrB| j}| j}nt }t }t| jtr| j	| }|d k	rt
|| j| j| j\}}| j|||B \}}	|j| qW | j	}
t||
}|S )N)r  r#  r  r   rq   r   rF   rG   r   r  _get_na_valuesrr   _infer_typesr   r0   )r   r   r5  arraysr   Zarrcol_na_valuescol_na_fvaluescol_namerM   rI   rB   rB   rC   r7    s&    


zParserBase._agg_indexc             C   s  i }x|j  D ]\}}	|d kr&d n
|j|d }
t|trJ|j|d }n|}| jrjt|||| j\}}nt t  }}|
d k	r|d k	rtj	d| dt
dd ytj|	|
}	W n: tk
r   tj|	t|jtj}tj|	|
|}	Y nX | j|	t||B dd\}}nt|pt|}|o&| }| j|	t||B |\}}|rt|| sbt|ry2t|rt| r|dkrtd| W n ttfk
r   Y nX | j|||}|||< |r|rtd	| d
| qW |S )Nz5Both a converter and dtype were specified for column z" - only the converter will be used   )r   F)try_num_boolr   z$Bool column has NA values in column zFilled z NA values in column )r   rW   rG   r   r   rC  rr   rF   r   r   r   r  Z	map_inferr>   r*   isinr   viewr   Zuint8Zmap_infer_maskrD  r&   r   r   r   r   r   r   _cast_typesprint)r   dctrq   r   r~   ru   Zdtypesr   r   r   Zconv_f	cast_typerF  rG  maskZcvalsna_countZis_str_or_ea_dtyperJ  rB   rB   rC   _convert_to_ndarrays  sX    





zParserBase._convert_to_ndarraysc             C   s  d}t |jjtjtjfrftj|t|}|j	 }|dkr^t
|rN|jtj}tj||tj ||fS |rt|jrytj||d}W n* ttfk
r   |}tj||d}Y qX t|j	 }n|}|jtjkrtj||d}|jtjko|r
tjtj|| j| jd}||fS )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
        r   F)rs   rt   )
issubclassrv   r   r   numberZbool_r*   rK  r   sumr"   ZastypeZfloat64Zputmasknanr$   r  Zmaybe_convert_numericr>   r   parsersZsanitize_objectsr)   Zobject_libopsZmaybe_convert_boolZasarrayrs   rt   )r   r   rq   rJ  rR  rQ  r   rB   rB   rC   rD  ?  s2    
zParserBase._infer_typesc             C   s  t |rbt|to|jdk	}t| r6| r6t|t}t|j j	 }t
j||j||| jd}nt|rt|}|j }y|j||dS  tk
r } ztd| d|W Y dd}~X nX nPyt||ddd}W n: tk
r } ztd| d	| |W Y dd}~X nX |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)rs   )rv   zExtension Array: zO must implement _from_sequence_of_strings in order to be used in parser methodsT)r   r  zUnable to convert column z	 to type )r   rG   r(   
categoriesr$   r   r   r-   uniqueZdropnar+   Z_from_inferred_categoriesZget_indexerrs   r   r'   Zconstruct_array_typeZ_from_sequence_of_stringsNotImplementedErrorr>   )r   r   rP  columnZ
known_catsZcatsZ
array_typer   rB   rB   rC   rM  r  s0    


zParserBase._cast_typesc          	   C   s6   | j d k	r.t|| j| j | j| j|| jd\}}||fS )N)r{   )rR   _process_date_conversionr  rm   r  r{   )r   rI   ra   rB   rB   rC   _do_date_conversions  s    
zParserBase._do_date_conversions)F)N)F)T)FNN)T)r   r   r   r   r
   r   r   r^   propertyr!  r#  r/  r2  r4  r;  r>  r6  r8  r7  rS  rD  rM  r_  rB   rB   rB   rC   r    s"   W0
:



J
37r  c               @   sT   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdd Z	dd Z
dddZd
S )r   z

    c                s  | _ |j }tj | |jd}|jdd kr|rt|trVt|d} jj	| t
|drzt
|d rzt||dd}d|d<  jdk	|d	< t|d
 \ _ _ j|d
< tj|f| _ jj _ jd k} jjd krd  _nLt jjdkr  j jj j j|\ _ _ _}nt jjd  _ jd krv jrd fddt jjD  _ntt jj _ jd d   _ jrt j j jdkrt j! j rt" j t jtkrfddt# jD  _t jtk rt" j  j$ j  j%   j _ j&s jj'dkrt( jrd _)t* j j j\} _ _ jd kr| _ jjd kr| rd gt j  _ jj'dk _+d S )NrL   rO   rbr]   r   )rL   newlinezutf-8FZallow_leading_colsr}   rU   r   c                s   g | ]} j  | qS rB   )rn   )r   r   )r   rB   rC   r    s    z+CParserWrapper.__init__.<locals>.<listcomp>r
  c                s$   g | ]\}}| ks| kr|qS rB   rB   )r   r   r(  )r}   rB   rC   r    s   T),r_   r   r  r   rW   rG   r   openr  r   r   r   rm   r  r}   r  rX  Z
TextReader_readerr  rI   rl   rE   r/  r  r  r   rn   r   Ztable_widthr  r  rF   issubsetr  r  r   _set_noconvert_columnsr!  leading_colsr   r  r+  r>  )r   srcr_   rL   r-  r  rB   )r   r}   rC   r     sf    





$

zCParserWrapper.__init__c             C   s@   x| j D ]}|j  qW y| jj  W n tk
r:   Y nX d S )N)r  r^   rd  r>   )r   r   rB   rB   rC   r^   )  s    zCParserWrapper.closec                s<  j  jdkr$tjj  n(tjs8jdkrHjdd nd fdd}tjtrxΈjD ].}t|trx|D ]}|| qW qp|| qpW ntjt	rxjj
 D ].}t|trx|D ]}|| qW q|| qW nHjr8tjtr"x0jD ]}|| qW njdk	r8|j dS )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	  r  Nc                s:   d k	rt | r|  } t | s* j| } jj|  d S )N)r!   r   rd  Zset_noconvert)r)  )rI   r   r}   rB   rC   _setH  s
    
z3CParserWrapper._set_noconvert_columns.<locals>._set)r  N)r  r  r   r}   sortr   rI   rG   rR   r   r   rm   )r   ri  r@   krB   )rI   r   r}   rC   rf  3  s4    


	



z%CParserWrapper._set_noconvert_columnsc             C   s   | j jt| d S )N)rd  set_error_bad_linesr=   )r   statusrB   rB   rC   rl  h  s    z"CParserWrapper.set_error_bad_linesNc       
         s  y| j j|}W n tk
r   | jrd| _| j| j}t|| j| j| j	j
dd\} }| j | j | jd k	r|| j  tt fdd|j }| |fS  Y nX d| _| j}| j jr| jrtdg }xTt| j jD ]D}| jd kr|j|}n|j| j| }| j||dd}|j| qW t|}| jd k	rD| j|}| j|}t|j }d	d
 t||D }| j||\}}nzt|j }t| j}| j|}| jd k	r| j|}dd |D }	dd
 t||D }| j||\}}| j||	|\}}| j|| j}|||fS )NFrv   )rv   c                s   | d  kS )Nr   rB   )item)r   rB   rC   <lambda>~  s    z%CParserWrapper.read.<locals>.<lambda>z file structure not yet supportedT)r5  c             S   s   i | ]\}\}}||qS rB   rB   )r   rk  r   vrB   rB   rC   
<dictcomp>  s    z'CParserWrapper.read.<locals>.<dictcomp>c             S   s   g | ]}|d  qS )rU   rB   )r   r)  rB   rB   rC   r    s    z'CParserWrapper.read.<locals>.<listcomp>c             S   s   i | ]\}\}}||qS rB   rB   )r   rk  r   rp  rB   rB   rC   rq    s    ) rd  r]   r   r  r2  r  _get_empty_metarm   r  r_   rW   r4  r  r}   _filter_usecolsr   filterr   rI   rg  r!  r\  r   r   _maybe_parse_datesr   r0   r  r,  r_  r   r;  )
r   rV   ra   rI   r   r   rE  r   r   r9  rB   )r   rC   r]   k  s`    









zCParserWrapper.readc                s>   t | j|  d k	r:t|t kr: fddt|D }|S )Nc                s$   g | ]\}}| ks| kr|qS rB   rB   )r   r   r?   )r}   rB   rC   r    s    z2CParserWrapper._filter_usecols.<locals>.<listcomp>)r  r}   rE   r  )r   rI   rB   )r}   rC   rs    s    zCParserWrapper._filter_usecolsc             C   sJ   t | jjd }d }| jjdkrB| jd k	rBt|| j| j\}}| _||fS )Nr   )r   rd  rl   rg  rm   r+  r  )r   rI   Z	idx_namesrB   rB   rC   _get_index_names  s    zCParserWrapper._get_index_namesTc             C   s   |r| j |r| j|}|S )N)r#  r  )r   r   r   r5  rB   rB   rC   ru    s    
z!CParserWrapper._maybe_parse_dates)N)T)r   r   r   r   r   r^   rf  rl  r]   rs  rv  ru  rB   rB   rB   rC   r     s   j
5
U	r   c              O   s   d|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.
    r   r   )r\   )argsr_   rB   rB   rC   
TextParser  s    6rx  c             C   s   t dd | D S )Nc             s   s"   | ]}|d ks|dkrdV  qdS )r   NrU   rB   )r   rp  rB   rB   rC   r   	  s    z#count_empty_vals.<locals>.<genexpr>)rV  )valsrB   rB   rC   count_empty_vals	  s    rz  c               @   s   e Zd Zdd Zdd Zdd Zd3dd	Zd
d Zd4ddZdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,Zd-d. Zd/d0 Zd5d1d2ZdS )6r   c                s  t j | d _g  _d _d _|d  _|d  _|d  _|d  _	t
 j	r` j	 _n fdd _t|d	  _|d
  _|d  _t jtrt j _|d  _|d  _|d  _|d  _|d  _t|d \ _}|d  _|d  _|d  _|d pd _d _d|kr4|d  _|d  _|d  _|d  _ |d  _!|d  _"|d  _#g  _$t%|d j j jd\}} j&j'| t(|d r j)| n| _d _*y j+ \ _, _- _.W n$ t/t0fk
r    j1   Y nX t2 j,d!kr@ j3 j, j4 j5\ _, _4 _5}t2 j, _-n j,d  _,t6 j, _7 j8s j9 j,\} _7 _,d" _: j4dkr| _4 j; j,  j<r j=  _>nd _>t2 j"d!krt0d# j!dkrt?j@d$ j" d% _Ant?j@d$ j! d& j" d% _AdS )'zN
        Workhorse function for processing nested list into DataFrame
        Nr   rL   rO   r   ro   c                s
   |  j kS )N)ro   )r)  )r   rB   rC   ro  ,	  s    z'PythonParser.__init__.<locals>.<lambda>rp   re   rg   rf   ri   rj   rk   rh   r}   r   r   r   rI   Fr   r~   ru   rv   rx   rz   ry   r$  )rL   rO   r   readlinerU   Tz'Only length-1 decimal markers supportedz[^-^0-9^z]+^)Br  r   ra   bufposline_posrL   rO   r   ro   r   skipfuncr  rp   re   rg   rG   r   rf   ri   rj   rk   rh   r  r}   r   r   r   Znames_passedr   r~   ru   rv   rx   rz   ry   Z_comment_linesr4   r  extendr   _make_reader_col_indices_infer_columnsr   num_original_columnsr  r   r>   r^   rE   r/  r  r  r   r  r!  _get_index_namer  r   rR   _set_no_thousands_columns_no_thousands_columnsrX   compilenonnum)r   r   r_   rM   r  r  rB   )r   rC   r   	  s    























zPythonParser.__init__c                s   t    fdd}tjtr\xƈjD ].}t|trNx|D ]}|| q<W q(|| q(W ntjtrx~jj D ].}t|trx|D ]}|| qW qt|| qtW n@jrtjtrx,jD ]}|| qW njd k	r|j  S )Nc                s*   t | r j|  n jjj|  d S )N)r!   addr   r   )r)  )noconvert_columnsr   rB   rC   ri  	  s    z4PythonParser._set_no_thousands_columns.<locals>._set)rF   rG   rR   r   r   r   rm   )r   ri  r@   rk  rB   )r  r   rC   r  	  s*    





z&PythonParser._set_no_thousands_columnsc       
         s:  j d kstdkrjr*tdG fdddtj}|}d k	rT|_ n j }j|ggd }x>jj	s| r j	d7  _	 j }j|ggd }qpW |d } j	d7  _	 j
d7  _
tj j|}|j |_ tjt||d}jjt| tj |dd}n fd	d
}	|	 }|_d S )NrU   z<Custom line terminators not supported in python parser (yet)c                   s4   e Zd Z jZ jZ jZ jZ jZ jZdZ	dS )z,PythonParser._make_reader.<locals>.MyDialect
N)
r   r   r   re   rg   rf   ri   rj   rh   rk   rB   )r   rB   rC   	MyDialect	  s   r  r   )r   T)r   strictc              3   sD    j  } tj}|j| j V  x D ]} |j| j V  q(W d S )N)r{  rX   r  splitstrip)linepat)r   r   rB   rC   rb   	  s
    

z(PythonParser._make_reader.<locals>._read)re   rE   rk   r>   r   Dialectr{  _check_commentsr  r~  r  Sniffersniffreaderr   r}  r  r   ra   )
r   r   r  Zdiar  linessniffedZline_rdrr  rb   rB   )r   r   r   rC   r  	  s4    		zPythonParser._make_readerNc             C   s  y| j |}W n" tk
r0   | jr*g }n Y nX d| _t| j}t|s| j| j}t|| j| j	| j
\}}}| j|| j}|||fS t|d }d }| jr|t|kr|d }|dd  }| j|}	| j|	}
| j| j}| j||
\}}
| j|
}
| j|
|	||\}}|||
fS )NFr   rU   )
_get_linesr   r  r   r  rE   r2  rr  rm   r  rv   r4  r  rz  r   _rows_to_cols_exclude_implicit_indexr   r_  _convert_datar;  )r   rowscontentr   rI   r   r   Zcount_empty_content_valsr:  r9  ra   rB   rB   rC   r]   	  s4    




zPythonParser.readc             C   sz   | j | j}| jrb| j}i }d}xTt|D ]2\}}x|| |krJ|d7 }q4W |||  ||< q*W ndd t||D }|S )Nr   rU   c             S   s   i | ]\}}||qS rB   rB   )r   rk  rp  rB   rB   rC   rq  1
  s    z8PythonParser._exclude_implicit_index.<locals>.<dictcomp>)r2  r  r>  rm   r  r,  )r   r9  rI   Zexcl_indicesra   offsetr   r   rB   rB   rC   r  $
  s    z$PythonParser._exclude_implicit_indexc             C   s   |d kr| j }| j|dS )N)r  )rT   r]   )r   r   rB   rB   rC   r   6
  s    zPythonParser.get_chunkc       
         s    fdd}| j }t jts* j}n
| j}i }i }t jtrx^ jD ]F} j| } j| }	t|tr| jkr j| }|||< |	||< qPW n j} j} j||| j	||S )Nc                sD   i }x:| j  D ].\}}t|tr4| jkr4 j| }|||< qW |S )zconverts col numbers to names)r   rG   r=   r  )mappingcleanr   rp  )r   rB   rC   _clean_mapping=
  s    
z2PythonParser._convert_data.<locals>._clean_mapping)
ru   rG   rv   r   rq   r   r=   r  rS  r~   )
r   ra   r  Z
clean_convZclean_dtypesZclean_na_valuesZclean_na_fvaluesr   Zna_valueZ	na_fvaluerB   )r   rC   r  ;
  s0    	




zPythonParser._convert_datac                s   j }d}d}t } jd k	r j}t|tttjfr`t|dk}|rjt||d d g }n
d}|g}g }x|t	|D ]n\}}	y$ j
 }
x j|	kr j }
qW W n tk
rR } z j|	k rtd|	 d jd  d||o|	dkr"|r  j  |jd gt|d   |||fS  j s4td| j d d  }
W Y d d }~X nX g g }xbt	|
D ]V\}}|d	kr|rd
| d| }n
d
| }|j| j| n
j| qfW | rB jrBtt}xt	D ]Z\}}|| }x2|dkr$|d ||< | d| }|| }qW ||< |d ||< qW nr|r|	|d krt} jd k	rtt jnd}t|}||kr|| |krd}d g|  jd g _|j |jfdd|D  t|dkrzt}qzW |r j  |d k	r jd k	r&t|t jksH jd krPt|t|d krPtdt|dkrftd jd k	r j|| nd  _t|}|g}n j||d }ny j
 }
W n@ tk
r } z"|std||d d  }
W Y d d }~X nX t|
}|}|sL jr, fddt|D g}ntt|g} j||d }nt jd ksft||kr~ j|g|}t|}nBt j rt|t jkrtd j|g| |g}|}|||fS )Nr   TrU   FzPassed header=z
 but only z lines in filezNo columns to parse from filer   z	Unnamed: Z_level_rd   c                s   h | ]} | qS rB   rB   )r   r   )this_columnsrB   rC   r   
  s    z.PythonParser._infer_columns.<locals>.<setcomp>zHNumber of passed names did not match number of header fields in the filez*Cannot pass names with multi-index columnsc                s   g | ]} j  | qS rB   )rn   )r   r   )r   rB   rC   r  
  s    z/PythonParser._infer_columns.<locals>.<listcomp>r*  r*  r*  r*  )rI   rF   rl   rG   r   r   r   r   rE   r  _buffered_liner  
_next_liner   r>   _clear_bufferr   r   r   r   r=   rm   r}  r   r}   r   _handle_usecolsr  rn   r   r   )r   rI   r  Zclear_bufferr  rl   Zhave_mi_columnsr   levelhrr  r   Zthis_unnamed_colsr   r   rH  r0  r   r1  lcr.  Zunnamed_countZncolsrB   )r   r  rC   r  h
  s    


 





 "

"zPythonParser._infer_columnsc                s   | j dk	rt| j r"t| j | ntdd | j D rt|dkrJtdg  xb| j D ]P}t|try j|j	| W q tk
r   t
| j | Y qX qV j| qVW n| j   fdd|D } | _|S )zb
        Sets self._col_indices

        usecols_key is used if there are string usecols.
        Nc             s   s   | ]}t |tV  qd S )N)rG   r   )r   urB   rB   rC   r     s    z/PythonParser._handle_usecols.<locals>.<genexpr>rU   z4If using multiple headers, usecols must be integers.c                s"   g | ]} fd dt |D qS )c                s   g | ]\}}| kr|qS rB   rB   )r   r   r(  )col_indicesrB   rC   r     s    z;PythonParser._handle_usecols.<locals>.<listcomp>.<listcomp>)r  )r   r]  )r  rB   rC   r     s   z0PythonParser._handle_usecols.<locals>.<listcomp>)r}   r   r  r  rE   r>   rG   r   r   r   r  r  )r   r   Zusecols_keyr   rB   )r  rC   r    s(    



zPythonParser._handle_usecolsc             C   s$   t | jdkr| jd S | j S dS )zH
        Return a line from buffer, filling buffer if required.
        r   N)rE   r}  r  )r   rB   rB   rC   r  &  s    
zPythonParser._buffered_linec             C   s   |s|S t |d ts|S |d s&|S |d d }|tkr>|S |d }t|dkr|d | jkrd}|d }|dd j|d }||| }t||d kr|||d d 7 }|g|dd  S t|dkr|dd gS dgS dS )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.
        r   rU   r   Nr   )rG   r   _BOMrE   rg   r   )r   Z	first_rowZ	first_eltZfirst_row_bomstartquoteendnew_rowrB   rB   rC   _check_for_bom/  s*    
zPythonParser._check_for_bomc             C   s   | pt dd |D S )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.
        c             s   s   | ]}| V  qd S )NrB   )r   r)  rB   rB   rC   r   q  s    z.PythonParser._is_line_empty.<locals>.<genexpr>)r   )r   r  rB   rB   rC   _is_line_emptyd  s    zPythonParser._is_line_emptyc             C   s  t | jtrx| j| jr*|  jd7  _qW xyp| j| j| j gd }|  jd7  _| j r|| j| j| jd  sx|r|P n | jr| j|g}|r|d }P W q. t	k
r   t
Y q.X q.W nx(| j| jr|  jd7  _t| j qW xt| j| jd d}|  jd7  _|d k	r| j|gd }| jrH| j|g}|rZ|d }P q| j|sX|rP qW | jdkrt| j|}|  jd7  _| jj| |S )NrU   r   )row_num)rG   ra   r   r  r~  r  r   r  _remove_empty_lines
IndexErrorr   r   _next_iter_liner  r  r}  r   )r   r  r   Z	orig_linerB   rB   rC   r  s  sJ    
zPythonParser._next_linec             C   s:   | j rt|n&| jr6d| d}tjj|| d  dS )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.
        zSkipping line z: r  N)r   r   r   r   stderrwrite)r   rA   r  baserB   rB   rC   _alert_malformed  s
    
zPythonParser._alert_malformedc             C   s   y
t | jS  tjk
rz } zR| js*| jrlt|}d|ksBd|krFd}| jdkr`d}|d| 7 }| j|| dS d}~X nX dS )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 bytezline contains NULzNULL byte detected. This byte cannot be processed in Python's native csv library at the moment, so please pass in engine='c' insteadr   zError 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)	r   ra   r   Errorr   r   r   rp   r  )r   r  erA   reasonrB   rB   rC   r    s    

zPythonParser._next_iter_linec             C   s   | j d kr|S g }xv|D ]n}g }xZ|D ]R}t|t s@| j |krL|j| q&|d |j| j  }t|dkrv|j| P q&W |j| qW |S )Nr   )ry   rG   r   r   findrE   )r   r  r   lrlr)  rB   rB   rC   r    s    



zPythonParser._check_commentsc             C   sT   g }xJ|D ]B}t |dksBt |dkr
t|d t sB|d j r
|j| 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.
        rU   r   )rE   rG   r   r  r   )r   r  r   r  rB   rB   rC   r    s    
z PythonParser._remove_empty_linesc             C   s    | j d kr|S | j|| j ddS )Nr   )r  searchreplace)rx   _search_replace_num_columns)r   r  rB   rB   rC   _check_thousands  s    
zPythonParser._check_thousandsc       	      C   s   g }x|D ]z}g }xft |D ]Z\}}t|t sX||ksX| jrH|| jksX| jj|j rd|j| q|j|j|| qW |j| q
W |S )N)	r  rG   r   r  r  r  r  r   r  )	r   r  r  r  r   r  r  r   r)  rB   rB   rC   r    s    
z(PythonParser._search_replace_num_columnsc             C   s$   | j td kr|S | j|| j ddS )Nrz   rd   )r  r  r  )rz   r   r  )r   r  rB   rB   rC   _check_decimal&  s    zPythonParser._check_decimalc             C   s
   g | _ d S )N)r}  )r   rB   rB   rC   r  .  s    zPythonParser._clear_bufferFc       	      C   sL  t |}t |}y| j }W n tk
r4   d}Y nX y| j }W n tk
rZ   d}Y nX d}|dk	r| jdk	rt|| j }|dk	rt|t|| j krt tt|| _| jdd | _xt|D ]}|j	d| qW t |}t|| _|||fS |dkr*d| _
| jdkr$t t|| _d}nt|| j| j\}}| _|||fS )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.
        Nr   FrU   T)r   r  r   rm   rE   r  r   r}  reversedinsertr>  r+  r  )	r   r   r  r  Z	next_lineZimplicit_first_colsr   Z
index_nameZcolumns_rB   rB   rC   r  3  s>    





zPythonParser._get_index_namec                s   j } jr|t j7 }tdd |D }||koF jdk	oF jd krF jrV jnd}g }t|}t|}g }x`|D ]X\}}	t|	}
|
|krƈ js j	rЈ j
|| |  }|j||
f  jrP qx|j|	 qxW xp|D ]h\}}
d| d|d  d|
 } jr2t jdkr2 jtjkr2d	}|d
| 7 } j||d  qW ttj||dj} jr jr fddt|D }n fddt|D }|S )Nc             s   s   | ]}t |V  qd S )N)rE   )r   rowrB   rB   rC   r   y  s    z-PythonParser._rows_to_cols.<locals>.<genexpr>Fr   z	Expected z fields in line rU   z, saw zXError could possibly be due to quotes being ignored when a multi-char delimiter is used.z. )Z	min_widthc                s6   g | ].\}}|t  jk s.|t  j  jkr|qS rB   )rE   rm   r  )r   r   a)r   rB   rC   r    s   z.PythonParser._rows_to_cols.<locals>.<listcomp>c                s   g | ]\}}| j kr|qS rB   )r  )r   r   r  )r   rB   rC   r    s    )r  r>  rE   rm   maxr}   rp   r  r   r   r~  r   re   rh   r   
QUOTE_NONEr  r   r  Zto_object_arrayT)r   r  Zcol_lenmax_lenZfootersZ	bad_linesiter_contentZcontent_lenr   r  Z
actual_lenr  rA   r  Zzipped_contentrB   )r   rC   r  s  sD    
zPythonParser._rows_to_colsc                s"   j }d }|d k	rPt j |krB j d |  j |d   } _ n|t j 8 }|d krt jtr jt jkrzt|d kr j jd  }t j}n  j j j|  } j| } jrڇ fddt|D }|j	| | _ng }y||d k	r,x"t
|D ]}|jt j qW |j	| n>d}x8 j j| d d}|d7 }|d k	r2|j| q2W W nN tk
r    jr fddt|D }|j	| t|dkr Y nX   jt|7  _g  _ n|} jr|d  j  } j|} jr j|} j|} j|S )Nc                s$   g | ]\}} j | j s|qS rB   )r  r~  )r   r   r  )r   rB   rC   r    s   z+PythonParser._get_lines.<locals>.<listcomp>r   rU   )r  c                s$   g | ]\}} j | j s|qS rB   )r  r~  )r   r   r  )r   rB   rC   r    s   )r}  rE   rG   ra   r   r~  r   ro   r  r  r   r   r   r  rp   r  r   r  r  r  )r   r  r  r   Znew_posrM   r  rB   )r   rC   r    sb    "










zPythonParser._get_lines)N)N)N)r   r   r   r   r  r  r]   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r>  r  r  r  rB   rB   rB   rC   r   	  s6    $?
(
- "	54'@Gr   c                s    fdd}|S )Nc                 s   d kr\t j| }ytjt|d d dj S  tk
rX   tjt j|d dS X ny,tj|  d d}t|t	j	rt
d|S  t
k
r   y tjt jt j| dddS  t
k
r   tf|  S X Y nX d S )	Nignore)utcr|   errorsr   cache)r|   )r  )r  r  zscalar parser)r`   r|   )r  )r   Zconcat_date_colstoolsZto_datetimer   Zto_numpyr>   r5  rG   datetime	Exceptionr7   )	date_colsstrsr   )rw   rQ   r|   r   rB   rC   	converter  s:    
z'_make_date_converter.<locals>.converterrB   )rQ   r|   r   rw   r  rB   )rw   rQ   r|   r   rC   r  	  s    'r  c                s   fdd}g }i }	|}
t |}t }|d ks:t|trB| |fS t|t rx|D ]}t|rt|trx|| krx|
| }||rqR|| | | |< qRt||| |
\}}}|| krtd| ||	|< |j| |j	| qRW nlt|t
rLx^|j D ]R\}}|| krtd| dt||| |
\}}}||	|< |j| |j	| qW | j	|	 |j| |sx&t |D ]}| j| |j| qpW | |fS )Nc                s$   t  tr|  kp"t to"| kS )N)rG   r   )colspec)rm   r  rB   rC   _isindex?  s    z*_process_date_conversion.<locals>._isindexz New date column already in dict zDate column z already in dict)r   rF   rG   r[   r%   r=   _try_convert_datesr>   r   r   r   r   r  r   rB  )	data_dictr  Z
parse_specrm   r  r   r{   r  Znew_colsZnew_datar  r  r  new_namer   Z	old_namesrM   r   rB   )rm   r  rC   r^  6  sN    	







r^  c       
         s   t |}g }xL|D ]D}||kr*|j| qt|trL||krL|j||  q|j| qW djdd |D } fdd|D }| | }	||	|fS )NrM   c             s   s   | ]}t |V  qd S )N)r   )r   r)  rB   rB   rC   r     s    z%_try_convert_dates.<locals>.<genexpr>c                s   g | ]}| kr | qS rB   rB   )r   r   )r  rB   rC   r    s    z&_try_convert_dates.<locals>.<listcomp>)rF   r   rG   r=   r   )
r`   r  r  r   colsetcolnamesr   r  Zto_parseZnew_colrB   )r  rC   r  {  s    
r  c             C   s   | d kr |rt } nt } t }nt| tr| j }i } x:|j D ].\}}t|sV|g}|rft|t B }|| |< q@W dd | j D }n*t| s| g} t| } |r| t B } t| }| |fS )Nc             S   s   i | ]\}}t ||qS rB   )_floatify_na_values)r   rk  rp  rB   rB   rC   rq    s    z$_clean_na_values.<locals>.<dictcomp>)	r   rF   rG   r   r   r   r#   _stringify_na_valuesr  )rq   rr   r   Zold_na_valuesrk  rp  rB   rB   rC   r     s,    
r   c       	      C   s   t |sd | |fS t| } t| }g }t|}xxt|D ]l\}}t|tr|j| xNt|D ]$\}}||kr^|||< | j| P q^W q8|| }| j| |j| q8W x.t|D ]"\}}t|tr||krd ||< qW || |fS )N)r   r   r  rG   r   r   rB  )	r   rm   r  Zcp_colsr  r   r   r"  r?   rB   rB   rC   r+    s*    




r+  c                s   t | } tts,pt t fddnFj }tdd x0|j D ]$\}}t|rb| | n|}||< qJW |d ks|dks|d krtg }nJfdd|D }	t	|	|d}|j
  x"t|D ]\}
}| j||
  qW fdd	| D }|| |fS )
Nc                  s    S )NrB   rB   )default_dtyperB   rC   ro    s    z!_get_empty_meta.<locals>.<lambda>c               S   s   t S )N)objectrB   rB   rB   rC   ro    s    Fc                s   g | ]}t g  | d qS ))rv   )r1   )r   r?   )rv   rB   rC   r    s    z#_get_empty_meta.<locals>.<listcomp>)rI   c                s   i | ]}t g  | d |qS ))rv   )r1   )r   rH  )rv   rB   rC   rq    s    z#_get_empty_meta.<locals>.<dictcomp>)r   rG   r   r  r   r   r   r!   r-   r0   rj  r  r   )r   rm   r  rv   Z_dtyperk  rp  r   r   ra   r   r(  r   rB   )r  rv   rC   rr    s$    

rr  c             C   sT   t  }xH| D ]@}y t|}tj|s.|j| W q tttfk
rJ   Y qX qW |S )N)rF   floatr   isnanr  r   r>   OverflowError)rq   r   rp  rB   rB   rC   r     s    


r  c             C   s   g }x| D ]}|j t| |j | yHt|}|t|krbt|}|j | d |j t| |j | W n tttfk
r   Y nX y|j t| W q
 tttfk
r   Y q
X q
W t|S )z3 return a stringified and numeric for these values z.0)r   r   r  r=   r   r>   r  rF   )rq   r   r)  rp  rB   rB   rC   r    s$    


r  c             C   sJ   t |tr>| |kr"||  ||  fS |r0tt fS t t fS n||fS dS )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)rG   r   r   rF   )r   rq   r   rr   rB   rB   rC   rC  &  s    

rC  c             C   sJ   t |}g }x8| D ]0}||kr*|j| qt|tr|j||  qW |S )N)rF   r   rG   r=   )r  r   r  r  r   rB   rB   rC   _get_col_namesI  s    

r  c               @   s6   e Zd ZdZdddZdddZddd	Zd
d ZdS )FixedWidthReaderz(
    A reader of fixed-width lines.
    Nr   c             C   s   || _ d | _|rd| nd| _|| _|dkr>| j||d| _n|| _t| jttfsht	dt
|j xd| jD ]Z}t|ttfot|dkot|d ttjt
d fot|d ttjt
d fspt	d	qpW d S )
Nz
z
	 rP   )r   ro   z;column specifications must be a list or tuple, input was a r   r   rU   zEEach column specification must be 2 element tuple or list of integers)r   bufferre   ry   detect_colspecsr   rG   r   r   r   r   r   rE   r=   r   r	  )r   r   r   re   ry   ro   r   r  rB   rB   rC   r   Y  s$    zFixedWidthReader.__init__c             C   sf   |dkrt  }g }g }x@t| jD ]2\}}||kr<|j| |j| t||kr"P q"W 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)rF   r  r   r   rE   r   r  )r   r   ro   Zbuffer_rowsZdetect_rowsr   r  rB   rB   rC   get_rowsw  s    


zFixedWidthReader.get_rowsc                s  dj dd  jD }tjd| d} j||}|s@tdttt|}t	j
|d td} jd k	r| fd	d
|D }x4|D ],}x&|j|D ]}	d||	j |	j < qW qW t	j|d}
d|
d< t	j||
A dkd }tt|d d d |dd d }|S )Nr   c             s   s   | ]}d | V  qdS )\NrB   )r   r)  rB   rB   rC   r     s    z3FixedWidthReader.detect_colspecs.<locals>.<genexpr>z([^z]+)z(No rows from which to infer column widthrU   )rv   c                s   g | ]}|j  jd  qS )r   )	partitionry   )r   r  )r   rB   rC   r    s    z4FixedWidthReader.detect_colspecs.<locals>.<listcomp>r   r   )r   re   rX   r  r  r   r  r  rE   r   zerosr=   ry   finditerr  r  Zrollwherer   r,  )r   r   ro   
delimiterspatternr  r  rQ  r  mZshiftededgesZ
edge_pairsrB   )r   rC   r    s"    

"z FixedWidthReader.detect_colspecsc                s`   j d k	r@ytj  W qJ tk
r<   d _ tj Y qJX n
tj  fddjD S )Nc                s$   g | ]\}} || j jqS rB   )r  re   )r   ZfrommZto)r  r   rB   rC   r    s    z-FixedWidthReader.__next__.<locals>.<listcomp>)r  r   r   r   r   )r   rB   )r  r   rC   r     s    

zFixedWidthReader.__next__)Nr   )N)r   N)r   r   r   r   r   r  r  r   rB   rB   rB   rC   r  T  s
   

&
r  c               @   s    e Zd ZdZdd Zdd ZdS )r   zl
    Specialization that Converts fixed-width fields into DataFrames.
    See PythonParser for details.
    c             K   s,   |j d| _|j d| _tj| |f| d S )Nr   r   )r   r   r   r   r   )r   r   r_   rB   rB   rC   r     s    zFixedWidthFieldParser.__init__c             C   s"   t || j| j| j| j| j| _d S )N)r  r   re   ry   ro   r   ra   )r   r   rB   rB   rC   r    s    z"FixedWidthFieldParser._make_readerN)r   r   r   r   r   r  rB   rB   rB   rC   r     s   r   )r   )rP   Nr   )N)NFFT)F)T)N)r   collectionsr   r   r   r  ior   r   r  rX   r   textwrapr   typingr   r   r	   r
   r   r   r   r   numpyr   Zpandas._libs.libZ_libsr  Zpandas._libs.opsopsrY  Zpandas._libs.parsersrX  r   Zpandas._libs.tslibsr   Zpandas._typingr   r   Zpandas.errorsr   r   r   r   Zpandas.util._decoratorsr   Zpandas.core.dtypes.castr   Zpandas.core.dtypes.commonr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   Zpandas.core.dtypes.dtypesr(   Zpandas.core.dtypes.missingr)   Zpandas.corer*   Zpandas.core.arraysr+   Zpandas.core.framer,   Zpandas.core.indexes.apir-   r.   r/   r0   Zpandas.core.seriesr1   Zpandas.core.toolsr2   r  Zpandas.io.commonr3   r4   r5   r6   Zpandas.io.date_convertersr7   r  r   r  Z_doc_read_csv_and_tablerD   rJ   rb   QUOTE_MINIMALr   r   r   r   r   r   r   rF   r   formatr   r   r   Iteratorr\   r   r[   r=   r   r  r  r  r  r  r  r   rx  rz  r   r  r^  r  r   r+  rr  r  r  rC  r  r  r   rB   rB   rB   rC   <module>   s  $Hx (
4\  M    2    9  ":       y
3
>
%!
,#j