B
    x\V             &   @   s  d Z ddlmZ ddlmZ ddlZddlZddlZddlZddl	m
Z
 ddlZddlZddlm  mZ ddlm  mZ ddlm  mZ ddlmZ ddlmZ ddlmZmZmZmZmZmZm Z 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l,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZEmFZFmGZGmHZH ddlImJZJ ddlKmLZM ddlNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZW ddlXmYZY e!dZZde
d[e\eOddd d Z]drddZ^dd  Z_d!d" Z`ddd#ejad$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(%Zbd%d$d$d%d$d$d%dd)Zcd&d*dd+Zdd,hZed-d.hZfd/diZgd/hZhdsd1d2Zieid3d0d4Zje)e]jkd3d5d6d7ejZjeid8d9d4Zle)e]jkd8d:d;d7elZldtd<d=ZmG d>d? d?ePZnd@dA ZodBdC ZpdDdE ZqdFdG ZrdHdI ZsdJdK ZtdLdM ZuG dNdO dOevZwG dPdQ dQewZxdRdS ZydTdU ZzG dVdW dWewZ{dudXdYZ|dvdZd[Z}d\d] Z~dwd^d_Zd`da ZdxdbdcZddde Zdfdg Zdhdi Zdjdk Zdldm ZG dndo doePZG dpdq dqe{ZdS )yzM
Module contains tools for processing files into DataFrames or other objects
    )print_function)defaultdictN)fill)parsing)	PY3StringIOlrangelzipmaprangestring_typesuzip)AbstractMethodErrorEmptyDataErrorParserErrorParserWarning)Appender)astype_nansafe)ensure_objectis_bool_dtypeis_categorical_dtypeis_dtype_equalis_extension_array_dtype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)	
_NA_VALUESBaseIteratorUnicodeReaderUTF8Recoder_get_handle_infer_compression_validate_header_argget_filepath_or_bufferis_file_like)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 <http://pandas.pydata.org/pandas-docs/stable/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 either
    ``pathlib.Path`` or ``py._path.local.LocalPath``.

    By file-like object, we refer to objects with a ``read()`` method, such as
    a file handler (e.g. via builtin ``open`` function) or ``StringIO``.
sep : str, default {_default_sep}
    Delimiter to use. If sep is None, the C engine cannot automatically detect
    the separator, but the Python parsing engine can, meaning the latter will
    be used and automatically detect the separator by Python's builtin sniffer
    tool, ``csv.Sniffer``. In addition, separators longer than 1 character and
    different from ``'\s+'`` will be interpreted as regular expressions and
    will also force the use of the Python parsing engine. Note that regex
    delimiters are prone to ignoring quoted data. Regex example: ``'\r\t'``.
delimiter : str, default ``None``
    Alias for sep.
header : int, list of int, default 'infer'
    Row number(s) to use as the column names, and the start of the
    data.  Default behavior is to infer the column names: if no names
    are passed the behavior is identical to ``header=0`` and column
    names are inferred from the first line of the file, if column
    names are passed explicitly then the behavior is identical to
    ``header=None``. Explicitly pass ``header=0`` to be able to
    replace existing names. The header can be a list of integers that
    specify row locations for a multi-index on the columns
    e.g. [0,1,3]. Intervening rows that are not specified will be
    skipped (e.g. 2 in this example is skipped). Note that this
    parameter ignores commented lines and empty lines if
    ``skip_blank_lines=True``, so ``header=0`` denotes the first line of
    data rather than the first line of the file.
names : array-like, optional
    List of column names to use. If file contains no header row, then you
    should explicitly pass ``header=None``. Duplicates in this list will cause
    a ``UserWarning`` to be issued.
index_col : int, sequence or bool, optional
    Column to use as the row labels of the DataFrame. If a sequence is given, a
    MultiIndex is used. If you have a malformed file with delimiters at the end
    of each line, you might consider ``index_col=False`` to force pandas to
    not use the first column as the index (row names).
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    )Zsubsequent_indentat"  '.
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.
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
    <http://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.

    .. versionadded:: 0.18.1 support for 'zip' and 'xz' compression.

thousands : str, optional
    Thousands separator.
decimal : str, default '.'
    Character to recognize as decimal point (e.g. use ',' for European data).
lineterminator : str (length 1), optional
    Character to break file into lines. Only valid with C parser.
quotechar : str (length 1), optional
    The character used to denote the start and end of a quoted item. Quoted
    items can include the delimiter and it will be ignored.
quoting : int or csv.QUOTE_* instance, default 0
    Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
    QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote : bool, default ``True``
   When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
   whether or not to interpret two consecutive quotechar elements INSIDE a
   field as a single ``quotechar`` element.
escapechar : str (length 1), optional
    One-character string used to escape other characters.
comment : str, optional
    Indicates remainder of line should not be parsed. If found at the beginning
    of a line, the line will be ignored altogether. This parameter must be a
    single character. Like empty lines (as long as ``skip_blank_lines=True``),
    fully commented lines are ignored by the parameter `header` but not by
    `skiprows`. For example, if ``comment='#'``, parsing
    ``#empty\na,b,c\n1,2,3`` with ``header=0`` will result in 'a,b,c' being
    treated as the header.
encoding : str, optional
    Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
    standard encodings
    <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.
tupleize_cols : bool, default False
    Leave a list of tuples on columns as is (default is to convert to
    a MultiIndex on the columns).

    .. deprecated:: 0.21.0
       This argument will be removed and will always convert to MultiIndex

error_bad_lines : bool, default True
    Lines with too many fields (e.g. a csv line with too many commas) will by
    default cause an exception to be raised, and no DataFrame will be returned.
    If False, then these "bad lines" will dropped from the DataFrame that is
    returned.
warn_bad_lines : bool, default True
    If error_bad_lines is False, and warn_bad_lines is True, a warning for each
    "bad line" will be output.
delim_whitespace : bool, default False
    Specifies whether or not whitespace (e.g. ``' '`` or ``'	'``) will be
    used as the sep. Equivalent to setting ``sep='\s+'``. If this option
    is set to True, nothing should be passed in for the ``delimiter``
    parameter.

    .. versionadded:: 0.18.1 support for the Python parser.

low_memory : bool, default True
    Internally process the file in chunks, resulting in lower memory use
    while parsing, but possibly mixed type inference.  To ensure no mixed
    types either set False, or specify the type with the `dtype` parameter.
    Note that the entire file is read into a single DataFrame regardless,
    use the `chunksize` or `iterator` parameter to return the data in chunks.
    (Only valid with C parser).
memory_map : bool, default False
    If a filepath is provided for `filepath_or_buffer`, map the file object
    directly onto memory and access the data directly from there. Using this
    option can improve performance because there is no longer any I/O overhead.
float_precision : str, optional
    Specifies which converter the C engine should use for floating-point
    values. The options are `None` for the ordinary converter,
    `high` for the high-precision converter, and `round_trip` for the
    round-trip converter.

Returns
-------
DataFrame or TextParser
    A comma-separated values (csv) file is returned as two-dimensional
    data structure with labeled axes.

See Also
--------
to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_fwf : Read a table of fixed-width formatted lines into DataFrame.

Examples
--------
>>> pd.{func_name}('data.csv')  # doctest: +SKIP
c             C   sX   dj | |d}|dk	rTt|r<t||kr2t|t|}nt|rL||ksTt||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)
    z+'{name:s}' must be an integer >={min_val:d})namemin_valN)formatr   int
ValueErrorr   )r8   valr9   msg r?   0lib/python3.7/site-packages/pandas/io/parsers.py_validate_integer[  s    
rA   c             C   s4   | dk	r0t | t t| kr0d}tj|tdd | S )am  
    Check if the `names` parameter contains duplicates.

    If duplicates are found, we issue a warning before returning.

    Parameters
    ----------
    names : array-like or None
        An array containing a list of the names used for the output DataFrame.

    Returns
    -------
    names : array-like or None
        The original `names` parameter.
    NzBDuplicate names specified. This will raise an error in the future.   )
stacklevel)lensetwarningswarnUserWarning)namesr>   r?   r?   r@   _validate_namesy  s
    rJ   c             C   s"  | dd}|dk	r.tdd| }||d< | dd}t| |}t| ||\} }}}||d< | dddk	rt|d trd	|d< | d
d}td| ddd}| dd}t	| dd t
| f|}	|s|r|	S z|	|}
W d|	  X |ry|   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lowerr2   r4   
isinstanceboolrA   rJ   TextFileReaderreadcloser<   )filepath_or_bufferkwdsrK   rN   rL   Zshould_closerR   rS   rU   parserdatar?   r?   r@   _read  s8    

rc   "TFrO      .)%	delimiter
escapechar	quotecharquotingdoublequoteskipinitialspacelineterminatorheader	index_colrI   prefixskiprows
skipfooterrU   	na_valueskeep_default_natrue_valuesfalse_values
convertersdtype	thousandscommentdecimalrQ   keep_date_coldayfirstrP   usecolsrS   verboserK   squeezerN   mangle_dupe_colstupleize_colsinfer_datetime_formatskip_blank_lines)delim_whitespace	na_filter
low_memory
memory_maperror_bad_lineswarn_bad_linesr   float_precisiond   )colspecsinfer_nrowswidthsrq   r   r   r   ,c          0      s   dkrd}n }|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t jdd d d d d dddtd dd f0 fd	d
	}|_|S )N
read_tableFrO   Tr   re   rd   r   c1       4   2      s  dkrF|dkr*|d kr*t jdtdd nt jdtdd |dkrF }|)d k	rj|d ko\| k}1t|1d}2nt }2|d kr||}|-r| krtd|d k	rd	}3nd
}d}3|2j|||)||3|%|&|#|$||"||||||||||| |'|!|||||||||
|||(||/|0||-|,|+|.|	|*||d0 t| |2S )Nr   FzAread_table is deprecated, use read_csv instead, passing sep='\t'.   )rC   z/read_table is deprecated, use read_csv instead.)sep_overridezXSpecified a delimiter with both sep and delim_whitespace=True; you can only specify one.Tc)0rf   enginedialectrN   engine_specifiedrj   rg   rh   ri   rk   rl   rm   rn   rI   ro   rp   rq   rr   rt   ru   rs   rx   ry   rz   rQ   r{   r|   rP   rU   rR   rS   rv   rw   r}   r~   rK   r   r   r   r   r   r   r   r   r   r   r   r   )rF   rG   FutureWarningdictr<   updaterc   )4r_   seprf   rm   rI   rn   r}   r   ro   r   rw   r   rv   rt   ru   rk   rp   rq   rU   rr   rs   r   r~   r   rQ   r   r{   rP   r|   rR   rS   rN   rx   rz   rl   rh   ri   rj   rg   ry   rK   r   r   r   r   r   r   r   r   r   r`   r   )default_sepr8   r?   r@   parser_f  s    C
z'_make_parser_function.<locals>.parser_f)csvQUOTE_MINIMAL_c_parser_defaults__name__)r8   r   r   r   r?   )r   r8   r@   _make_parser_function  sj    hr   read_csv)r   z8Read a comma-separated values (csv) file into DataFrame.z',')Z	func_nameZsummaryZ_default_sepr   	zRead general delimited file into DataFrame.

.. deprecated:: 0.24.0
Use :func:`pandas.read_csv` instead, passing ``sep='\t'`` if necessary.z'\\t' (tab-stop)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 ]}|||| f ||7 }qJW ||d< ||d< d|d	< t| |S )
a[  
    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
    <http://pandas.pydata.org/pandas-docs/stable/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 either
        ``pathlib.Path`` or ``py._path.local.LocalPath``.

        By file-like object, we refer to objects with a ``read()`` method,
        such as a file handler (e.g. via builtin ``open`` function)
        or ``StringIO``.
    colspecs : list of tuple (int, int) or 'infer'. optional
        A list of tuples giving the extents of the fixed-width
        fields of each line as half-open intervals (i.e.,  [from, to[ ).
        String value 'infer' can be used to instruct the parser to try
        detecting the column specifications from the first 100 rows of
        the data which are not being skipped via skiprows (default='infer').
    widths : list of int, optional
        A list of field widths which can be used instead of 'colspecs' if
        the intervals are contiguous.
    infer_nrows : int, default 100
        The number of rows to consider when letting the parser determine the
        `colspecs`.

        .. versionadded:: 0.24.0
    **kwds : optional
        Optional keyword arguments can be passed to ``TextFileReader``.

    Returns
    -------
    DataFrame or TextParser
        A comma-separated values (csv) file is returned as two-dimensional
        data structure with labeled axes.

    See Also
    --------
    to_csv : Write DataFrame to a comma-separated values (csv) file.
    read_csv : Read a comma-separated values (csv) file into DataFrame.

    Examples
    --------
    >>> pd.read_fwf('data.csv')  # doctest: +SKIP
    Nz&Must specify either colspecs or widths)NrO   z4You must specify only one of 'widths' and 'colspecs'r   r   r   z
python-fwfr   )r<   appendrc   )r_   r   r   r   r`   colwr?   r?   r@   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}|d|| _|dd k	r|d }|t krXt|}xdD ]}yt||}W n( tk
r   tdj	|d dY nX t
| }|||}	g }
|	|kr|	|krd	j	||	|d
}|dkr|dds|
| |
rtjd|
tdd |||< q^W |drX|ds<|drDtd|drXtd|dddkr|dd kr~dnd |d< || _|| _d | _d| _| |}|dd | _|dd | _|dd| _| ||| _| ||\| _| _d|kr|d | jd< | | j d S )NTpythonFr   r   )rf   rj   rg   rk   rh   ri   z$Invalid dialect '{dialect}' provided)r   zConflicting values for '{param}': '{val}' was provided, but the dialect specifies '{diaval}'. Using the dialect-specified value.)paramr=   Zdiavalrf   r   z

r   )rC   rq   rR   rS   z*'skipfooter' not supported for 'iteration'rU   z''skipfooter' not supported with 'nrows'rm   rO   rI   r   r   has_index_names)frV   _engine_specifiedr   Zlist_dialectsZget_dialectgetattrAttributeErrorr<   r:   _parser_defaultspopr   rF   rG   joinr   orig_optionsr   _engine_currow_get_options_with_defaultsrS   rU   r   _check_file_or_buffer_clean_optionsoptions_make_engine)selfr   r   r`   r   r   r   Zdialect_valparser_defaultZprovidedZconflict_msgsr>   r   r?   r?   r@   __init__-  sb    




zTextFileReader.__init__c             C   s   | j   d S )N)r   r^   )r   r?   r?   r@   r^     s    zTextFileReader.closec             C   s  | j }i }x@ttD ]2\}}|||}|dkr@|s@tdq|||< qW xttD ]r\}}||kr|| }|dkr||krd|kr|tkrq|t||krqtd||f nt||}|||< qXW |dkrx&tt	D ]\}}|||||< qW |S )Nr   z3Setting mangle_dupe_cols=False is not supported yetr   r   z1The %r option is not supported with the %r enginez
python-fwf)
r   compat	iteritemsr   rV   r<   r   _python_unsupported_deprecated_defaults_fwf_defaults)r   r   r`   r   argnamedefaultvaluer?   r?   r@   r     s2    
z)TextFileReader._get_options_with_defaultsc             C   s6   t |r2trdnd}|dkr2t||s2d}t||S )N__next__nextr   z<The 'python' engine cannot iterate through this file buffer.)r5   r   hasattrr<   )r   r   r   Z	next_attrr>   r?   r?   r@   r     s    z$TextFileReader._check_file_or_bufferc             C   s  |  }| j}d }|d }|d }|dkr>|d dkr>d}d}t pHd}|d krh|sh|dkrfd	}d}n|d k	rt|d
kr|dkr|dkrd|d< |d= n|dkrd}d}nz|rd|krd|d< nd|d k	r(d}	yt||d
krd}	W n tk
r   d}	Y nX |	s(|dkr(dj|d}d}|d }
|
d k	r|t|
t	t
j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rxBtD ]:}|r|| t| krdj||d}t|||= qW |rtjd|tdd |d }|d }|d }|d }|d }t|d  d }xdtD ]\}t| }t| }d!j|d"}|d#kr|d$7 }||||kr||d% 7 }n|||< qXW |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	rRt|tsVt d(t!|j"ni }|d) }t#||\}}|dkrt$|rt%|}|d krt& }nt'|st&|}||d< ||d< ||d< ||d*< ||d< ||fS )+Nrf   r   r   rq   r   z*the 'c' engine does not support skipfooterr   zutf-8zDthe 'c' engine does not support sep=None with delim_whitespace=FalserT   z\s+T)r   z
python-fwfzxthe 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)Fzithe separator encoded in {encoding} is > 1 char long, and the 'c' engine does not support such separators)rK   rh      zxord(quotechar) > 127, meaning the quotechar is larger than one byte, and the 'c' engine does not support such quotecharszFalling back to the 'python' engine because {reason}, but this causes {option!r} to be ignored as it is not supported by the 'python' engine.)reasonZoptionzjFalling back to the 'python' engine because {0}; you can avoid this warning by specifying engine='python'.   )rC   rn   rI   rv   rr   rp   rm    zQThe '{arg}' argument has been deprecated and will be removed in a future version.)argr   z; Column tuples will then always be converted to MultiIndex.z

r   z)The value of index_col couldn't be 'True'z=Type converters must be a dict or subclass, input was a {0!r}rs   
na_fvalues)(copyr   sysgetfilesystemencodingrD   encodeUnicodeDecodeErrorr:   rZ   strr   	text_typebytesordr<   _c_unsupportedr   r   rF   rG   r   r3   _deprecated_argsr   rV   r   _is_index_collisttuplenpndarrayr   	TypeErrortyper   _clean_na_valuesr   r   rE   callable)r   r   r   resultr   Zfallback_reasonr   r   rK   Z
encodeablerh   r   r>   rn   rI   rv   rr   rp   Zdepr_warningr   Zdepr_defaultrs   r   r?   r?   r@   r     s    



















zTextFileReader._clean_optionsc             C   s,   y|   S  tk
r&   |    Y nX d S )N)	get_chunkStopIterationr^   )r   r?   r?   r@   r   Y  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j|d|| jf| j| _d S )Nr   r   z
python-fwfzKUnknown engine: {engine} (valid options are "c", "python", or "python-fwf"))r   )CParserWrapperr   r   r   PythonParserFixedWidthFieldParserr<   r:   )r   r   klassr?   r?   r@   r   `  s    
zTextFileReader._make_enginec             C   s   t | d S )N)r   )r   r?   r?   r@   _failover_to_pythonn  s    z"TextFileReader._failover_to_pythonc             C   s   t d|}| j|}| |\}}}|d kr`|rZttt|}t| j	| j	| }qhd}nt|}t
|||d}|  j	|7  _	| jrt|jdkr||jd   S |S )NrU   r   )columnsindexrT   )rA   r   r]   _create_indexrD   r   r   Z
itervaluesr)   r   r&   r   r   r   )r   rU   retr   r   col_dictnew_rowsZdfr?   r?   r@   r]   q  s    
zTextFileReader.readc             C   s   |\}}}|||fS )Nr?   )r   r   r   r   r   r?   r?   r@   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)rU   )rS   rU   r   r   minr]   )r   sizer?   r?   r@   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   r?   r?   r?   r@   r\   &  s   
T' 

r\   c             C   s   | d k	o| dk	S )NFr?   )r   r?   r?   r@   r     s    r   c             C   s&   t | o$t| t o$tdd | D S )a5  
    Check whether or not the `columns` parameter
    could be converted into a MultiIndex.

    Parameters
    ----------
    columns : array-like
        Object which may or may not be convertible into a MultiIndex

    Returns
    -------
    boolean : Whether or not columns could become a MultiIndex
    c             s   s   | ]}t |tV  qd S )N)rZ   r   ).0r   r?   r?   r@   	<genexpr>  s    z,_is_potential_multi_index.<locals>.<genexpr>)rD   rZ   r(   all)r   r?   r?   r@   _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 r?   r?   )r   ir8   )r}   r?   r@   	<setcomp>  s    z$_evaluate_usecols.<locals>.<setcomp>)r   	enumerate)r}   rI   r?   )r}   r@   _evaluate_usecols  s    r   c                s2    fdd| D }t |dkr.tdj|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 r?   r?   )r   r   )rI   r?   r@   
<listcomp>  s    z+_validate_usecols_names.<locals>.<listcomp>r   zGUsecols do not match columns, columns expected but not found: {missing})missing)rD   r<   r:   )r}   rI   r   r?   )rI   r@   _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<   )rq   r?   r?   r@   _validate_skipfooter_arg  s
    r   c             C   sx   d}| dk	rpt | r| dfS t| s,t|tj| dd}|dkrJt|t| } |dkrhdd | D } | |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unicoder  c             S   s   h | ]}| d qS )zutf-8)r   )r   r   r?   r?   r@   r   +  s    z(_validate_usecols_arg.<locals>.<setcomp>)r   r   r<   libZinfer_dtyperE   )r}   r>   usecols_dtyper?   r?   r@   _validate_usecols_arg  s    r  c             C   sB   d}| dk	r>t | r(t| 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   rZ   r   r   )rQ   r>   r?   r?   r@   _validate_parse_dates_arg1  s    

r	  c               @   s   e Zd Z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  | d| _d | _|dd | _| dd | _t | _d | _d | _	t
|dd| _|dd | _|dd| _|dd| _| d	| _| d
| _| dd| _| dd| _| d| _| d| _| dd| _| dd| _|dd| _t| j| j| jd| _| d| _t| jtttjfrt t!t"| jsFt#d| drZt#d| drnt#d| jd k	rt| jtttjf}|rt t!t"| jst"| jst#dn | jd k	rt"| jst#dd| _$d| _%g | _&d S )NrI   ro   rn   rQ   FrP   r|   r{   rr   r   r   rs   Trt   ru   r   r   r   )rP   r|   r   rm   z*header must be integer or list of 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 header)'rV   rI   
orig_namesr   ro   rn   rE   unnamed_colsindex_names	col_namesr	  rQ   rP   r|   r{   rr   r   r   rs   rt   ru   r   r   r   _make_date_converter
_date_convrm   rZ   r   r   r   r   r   r
   r   r<   _name_processed_first_chunkhandles)r   r`   Zis_sequencer?   r?   r@   r   H  sZ    


zParserBase.__init__c             C   s   x| j D ]}|  qW d S )N)r  r^   )r   r   r?   r?   r@   r^     s    zParserBase.closec             C   s6   t | jtp4t | jto4t| jdko4t | jd tS )Nr   )rZ   rQ   r   r   rD   )r   r?   r?   r@   _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)rZ   rQ   r[   r  rn   r   )r   r   r8   jr?   r?   r@   _should_parse_dates  s    




zParserBase._should_parse_datesFc       	         s2  t |dk r|d |||fS j}|dkr.g }t|tttjfsF|g}t||d}t	|jj
\}}}t |d fdd t fdd|D  }|| }xNtt |d D ]:tfd	d
|D rtdddd
 jD  qW t |rfdd|D }ndgt | }d}||||fS )zv extract and return the names, index_names, col_names
            header is a list-of-lists returned from the parsers r   r   Nc                s   t  fddtD S )Nc             3   s   | ]}|kr | V  qd S )Nr?   )r   r   )rsicr?   r@   r     s    zMParserBase._extract_multi_indexer_columns.<locals>.extract.<locals>.<genexpr>)r   r   )r  )field_countr  )r  r@   extract  s    z:ParserBase._extract_multi_indexer_columns.<locals>.extractc                s   g | ]} |qS r?   r?   )r   r  )r  r?   r@   r     s    z=ParserBase._extract_multi_indexer_columns.<locals>.<listcomp>c             3   s"   | ]}t |  jkV  qd S )N)r   Zto_strr  )r   r   )nr   r?   r@   r     s    z<ParserBase._extract_multi_indexer_columns.<locals>.<genexpr>zDPassed header=[%s] are too many rows for this multi_index of columnsr   c             s   s   | ]}t |V  qd S )N)r   )r   xr?   r?   r@   r     s    c                s2   g | ]*}t |d  r*|d   jkr*|d  ndqS )r   N)rD   r  )r   r  )r   r?   r@   r     s   T)rD   rn   rZ   r   r   r   r   rE   r   _clean_index_namesr  r	   r   r   r   r   rm   )	r   rm   r  r  passed_namesicrI   rn   r   r?   )r  r  r  r   r  r@   _extract_multi_indexer_columns  s6    



z)ParserBase._extract_multi_indexer_columnsc             C   s   | j rt|}tt}t|}xt|D ]v\}}|| }xP|dkr|d ||< |rr|d d d|d |f f }nd||f }|| }q:W |||< |d ||< q(W |S )Nr   rT   r  z%s.%d)r   r   r   r;   r   r   )r   rI   countsZis_potential_mir   r   	cur_countr?   r?   r@   _maybe_dedup_names  s    
 zParserBase._maybe_dedup_namesNc             C   s   t |rtj||d}|S )N)rI   )r   r(   Zfrom_tuples)r   r   r  r?   r?   r@   _maybe_make_multi_index_columns  s    z*ParserBase._maybe_make_multi_index_columnsc             C   s   t | jr| jsd }nh| js4| ||}| |}nJ| jr~| jsdtt|| j| j\| _	}| _d| _| 
||}| j|dd}|rt|t| }||d | }| || j}||fS )NTF)try_parse_dates)r   rn   r  _get_simple_index
_agg_indexr  r  r   r  r  _get_complex_date_indexrD   Z	set_namesr%  r  )r   rb   alldatar   indexnamerowr   rL   Zcoffsetr?   r?   r@   _make_index   s$    zParserBase._make_indexc             C   st   dd }g }g }x.| j D ]$}||}|| |||  qW x.tt|D ]}|| | jsN|| qNW |S )Nc             S   s    t | tjs| S td|  d S )NzIndex %s invalid)rZ   r   r   r<   )r   r?   r?   r@   ix  s    z(ParserBase._get_simple_index.<locals>.ix)rn   r   reversedsortedr   _implicit_index)r   rb   r   r-  	to_remover   idxr   r?   r?   r@   r'    s    

zParserBase._get_simple_indexc       	         sr    fdd}g }g }x.| j D ]$}||}|| |||  qW x(tt|D ]}||  | qRW |S )Nc                sN   t | tjr| S  d kr(tdt|  x t D ]\}}|| kr2|S q2W d S )Nz+Must supply column order to use %s as index)rZ   r   r   r<   r   r   )Zicolr   r   )r  r?   r@   	_get_name4  s    z5ParserBase._get_complex_date_index.<locals>._get_name)rn   r   r.  r/  r   remove)	r   rb   r  r3  r1  r   r2  r8   r   r?   )r  r@   r)  3  s    

z"ParserBase._get_complex_date_indexTc             C   s   g }xt |D ]\}}|r.| |r.| |}| jrB| j}| j}nt }t }t| jtr| j	| }|d k	rt
|| j| j| j\}}| |||B \}}	|| qW | j	}
t||
}|S )N)r   r  r  r   rr   r   rE   rZ   r   r  _get_na_valuesrs   _infer_typesr   r*   )r   r   r&  arraysr   Zarrcol_na_valuescol_na_fvaluescol_namerL   rI   r?   r?   r@   r(  O  s(    



zParserBase._agg_indexc          
   C   s  i }xt |D ]\}}	|d kr(d n
||d }
t|trL||d }n|}| jrlt|||| j\}}nt t  }}|
d k	r|d k	rt	j
d|tdd yt|	|
}	W n: tk
r   t|	t|tj}t|	|
|}	Y nX | j|	t||B dd\}}nt|pt|}|o&| }| |	t||B |\}}|rt||r`t|ry2t|rt|s|dkrtdj|dW n ttfk
r   Y nX | |||}|||< |r|rt d	|t!|f  qW |S )
NzZBoth a converter and dtype were specified for column {0} - only the converter will be used   )rC   F)try_num_boolr   z,Bool column has NA values in column {column})columnz Filled %d NA values in column %s)"r   r   rV   rZ   r   r   r5  rs   rE   rF   rG   r:   r   r  Z	map_inferr<   r$   isinr   Zviewr   Zuint8Zmap_infer_maskr6  r    r   r   r   r   r   r   _cast_typesprintr   )r   Zdctrr   r   r~   rv   Zdtypesr   r   valuesZconv_f	cast_typer8  r9  maskZcvalsna_countZis_str_or_ea_dtyper<  r?   r?   r@   _convert_to_ndarraysm  sZ    







zParserBase._convert_to_ndarraysc             C   s  d}t |jjtjtjfrft|t|}|	 }|dkr^t
|rN|tj}t||tj ||fS |ryt||d}t|	 }W q tk
r   |}|jtjkrt||d}Y qX n|}|jtjkrt||d}|jtjkr
|r
tjt|| j| jd}||fS )aW  
        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)rt   ru   )
issubclassrw   r   r   ZnumberZbool_r$   r>  r   sumr   ZastypeZfloat64Zputmasknanr  Zmaybe_convert_numericr#   	ExceptionZobject_parsersZsanitize_objectslibopsZmaybe_convert_boolZasarrayrt   ru   )r   rA  rr   r<  rD  rC  r   r?   r?   r@   r6    s4    
zParserBase._infer_typesc             C   s   t |r^t|to|jdk	}t|s2|s2t|t}t| 	 }t
j||||| jd}nt|rt|}| }y|j||dS  tk
r   tdj|dY qX n:yt||ddd}W n$ tk
r   td||f Y 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)rt   )rw   zdExtension Array: {ea} must implement _from_sequence_of_strings in order to be used in parser methods)ZeaT)r   r  z&Unable to convert column %s to type %s)r   rZ   r"   Z
categoriesr   r   r   r'   uniqueZdropnar%   Z_from_inferred_categoriesZget_indexerrt   r   r!   Zconstruct_array_typeZ_from_sequence_of_stringsNotImplementedErrorr:   r<   )r   rA  rB  r=  Z
known_catsZcatsZ
array_typer?   r?   r@   r?    s4    


zParserBase._cast_typesc          	   C   s6   | j d k	r.t|| j| j | j| j|| jd\}}||fS )N)r{   )rQ   _process_date_conversionr  rn   r  r{   )r   rI   rb   r?   r?   r@   _do_date_conversions  s
    
zParserBase._do_date_conversions)F)N)F)T)FNN)T)r   r   r   r   r^   propertyr  r  r!  r$  r%  r,  r0  r'  r)  r(  rE  r6  r?  rO  r?   r?   r?   r@   r
  F  s"   C
6


 
B
/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  | _ | }t | |dd krrd|dp6dkrrt|tjr\t|d} j	
| t||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|\ _ _ _}nt jjd  _ jd krb jrT fddt jjD  _nt jj _ jd d   _ jr t  j j jdkrt!" jst# j t jtkrfddt$ jD  _t jtk r t# j  %   j _ j&s jj'dkrft( jrfd _)t* j j j\} _ _ jd krf| _ jjd kr|sd gt j  _ jj'dk _+d S )NrN   zutf-16rK   r   rbzutf-8FZallow_leading_colsr}   rT   r   c                s   g | ]}d  j |f qS )z%s%d)ro   )r   r   )r   r?   r@   r   R  s   z+CParserWrapper.__init__.<locals>.<listcomp>r  c                s$   g | ]\}}| ks| kr|qS r?   r?   )r   r   r  )r}   r?   r@   r   j  s    T),r`   r   r
  r   rV   rZ   r   r   openr  r   r0   rn   r  r}   r  rJ  Z
TextReader_readerr  rI   rm   rD   r!  r  r  r   ro   r   Ztable_widthr   r  r   rE   issubsetr   r   _set_noconvert_columnsr  leading_colsr   r  r  r0  )r   srcr`   r  r  r?   )r   r}   r@   r   &  sj    





zCParserWrapper.__init__c             C   s@   x| j D ]}|  qW y| j  W n tk
r:   Y nX d S )N)r  r^   rS  r<   )r   r   r?   r?   r@   r^     s    zCParserWrapper.closec                s<  j  jdkr$t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
 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  NNc                s:   d k	rt | r|  } t | s* | } j|  d S )N)r   r   rS  Zset_noconvert)r  )rI   r   r}   r?   r@   _set  s
    
z3CParserWrapper._set_noconvert_columns.<locals>._set)r  r  r   r}   sortr   rI   rZ   rQ   r   rA  rn   )r   rX  r=   kr?   )rI   r   r}   r@   rU    s6    




	



z%CParserWrapper._set_noconvert_columnsc             C   s   | j t| d S )N)rS  set_error_bad_linesr;   )r   Zstatusr?   r?   r@   r[    s    z"CParserWrapper.set_error_bad_linesNc       
   
      s  y| j |}W n tk
r   | jrd| _| | j}t|| j| j| j	
dd\} }|  | j | jd k	r||   tt fdd| }| |fS  Y nX d| _| j}| j jr| jrtdg }xTt| j jD ]D}| jd kr||}n|| j| }| j||dd}|| qW t|}| jd k	rD| |}| |}t| }d	d
 t||D }| ||\}}nzt| }t| j}| |}| jd k	r| |}dd |D }	dd
 t||D }| ||\}}| ||	|\}}| || j}|||fS )NFrw   )rw   c                s   | d  kS )Nr   r?   )item)r   r?   r@   <lambda>  s    z%CParserWrapper.read.<locals>.<lambda>z file structure not yet supportedT)r&  c             S   s   i | ]\}\}}||qS r?   r?   )r   rZ  r   vr?   r?   r@   
<dictcomp>   s    z'CParserWrapper.read.<locals>.<dictcomp>c             S   s   g | ]}|d  qS )rT   r?   )r   r  r?   r?   r@   r     s    z'CParserWrapper.read.<locals>.<listcomp>c             S   s   i | ]\}\}}||qS r?   r?   )r   rZ  r   r^  r?   r?   r@   r_    s    ) rS  r]   r   r  r$  r  _get_empty_metarn   r  r`   rV   r%  r  r}   _filter_usecolsr   filteritemsrI   rV  r  rM  r   r   _maybe_parse_datesr   r*   r/  r   rO  r   r,  )
r   rU   rb   rI   r   r   r7  r   rA  r*  r?   )r   r@   r]     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 r?   r?   )r   r   r8   )r}   r?   r@   r      s    z2CParserWrapper._filter_usecols.<locals>.<listcomp>)r   r}   rD   r   )r   rI   r?   )r}   r@   ra    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   rS  rm   rV  rn   r  r  )r   rI   Z	idx_namesr?   r?   r@   _get_index_names$  s    zCParserWrapper._get_index_namesTc             C   s   |r|  |r| |}|S )N)r  r  )r   rA  r   r&  r?   r?   r@   rd  /  s    
z!CParserWrapper._maybe_parse_dates)N)T)r   r   r   r   r   r^   rU  r[  r]   ra  re  rd  r?   r?   r?   r@   r   !  s   `
6
S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`   r?   r?   r@   
TextParser5  s    6rg  c             C   s   t dd | D S )Nc             s   s"   | ]}|d ks|dkrdV  qdS )r   NrT   r?   )r   r^  r?   r?   r@   r   p  s    z#count_empty_vals.<locals>.<genexpr>)rG  )Zvalsr?   r?   r@   count_empty_valso  s    rh  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  | d _g  _d _d _|d  _|d  _|d  _|d  _	t
 j	r` j	 _n fdd _t|d	  _|d
  _|d  _t jtjrt j _|d  _|d  _|d  _|d  _|d  _t|d \ _}|d  _|d  _|d  _|d pd _d _d|kr6|d  _|d  _ |d  _!|d  _"|d  _#|d  _$|d  _%g  _&t'rdnd}t(|| j j jd \}} j)*| t+|d!rƈ ,| n| _d _- . \ _/ _0 _1t2 j/d"kr& 3 j/ j4 j5\ _/ _4 _5}t2 j/ _0n j/d  _/t6 j/ _7 j8st 9 j/\} _7 _/d# _: j4dkrt| _4 j;r <  _=nd _=t2 j$d"krt>d$ j#dkrt?@d% j$  _Ant?@d& j# j$f  _AdS )'z
        Workhorse function for processing nested list into DataFrame

        Should be replaced by np.genfromtxt eventually?
        Nr   rK   rN   r   rp   c                s
   |  j kS )N)rp   )r  )r   r?   r@   r]    s    z'PythonParser.__init__.<locals>.<lambda>rq   rf   rh   rg   rj   rk   rl   ri   r}   r   r   r   rI   Fr   r~   rv   rw   rx   rz   ry   r  rQ  )rK   rN   r   readlinerT   Tz'Only length-1 decimal markers supportedz[^-^0-9^%s]+z[^-^0-9^%s^%s]+)Br
  r   rb   bufposline_posrK   rN   r   rp   r   skipfuncr   rq   rf   rh   rZ   r   r   r   rg   rj   rk   rl   ri   r  r}   r   r   r   Znames_passedr   r~   rv   rw   rx   rz   ry   Z_comment_linesr   r1   r  extendr   _make_reader_col_indices_infer_columnsr   num_original_columnsr  rD   r!  r  r  r   r  r  _get_index_namer  rQ   _set_no_thousands_columns_no_thousands_columnsr<   rW   compilenonnum)r   r   r`   rL   moder  r  r?   )r   r@   r   u  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 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 |  n j|  d S )N)r   addr   r   )r  )noconvert_columnsr   r?   r@   rX    s    z4PythonParser._set_no_thousands_columns.<locals>._set)rE   rZ   rQ   r   r   rA  rn   )r   rX  r=   rZ  r?   )rz  r   r@   rt    s*    





z&PythonParser._set_no_thousands_columnsc       	         sn  j d kstdkrNjr*tdG fdddtj}|}d}d k	rZd}|_ |r  }x&jr jd7  _  }qjW 	|gd } jd7  _ j
d7  _
t |}|j |_ jd k	rjttt||jd njttjt||d	 jd k	r<t |jdd
}ntj |dd}n fdd}| }|_d S )NrT   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   rf   rh   rg   rj   rk   ri   rl   r?   )r   r?   r@   	MyDialect	  s   r|  TFr   )r   rK   )r   )r   rK   strict)r   r}  c              3   s\      } tjr jr | j} t}||  V  x D ]} ||  V  q@W d S )N)	ri  r   PY2rK   decoderW   rv  splitstrip)lineZpat)r   r   r   r?   r@   rc   D	  s    

z(PythonParser._make_reader.<locals>._read)rf   rD   rl   r<   r   ZDialectri  rm  rk  _check_commentsrl  ZSnifferZsniffrK   rj  rn  r   r/   r   readerrb   )	r   r   r|  ZdiaZ	sniff_sepr  Zsniffedr  rc   r?   )r   r   r   r@   ro  	  sH    	



zPythonParser._make_readerNc             C   s  y|  |}W n" tk
r0   | jr*g }n Y nX d| _t| j}t|s| | j}t|| j| j	| j
\}}}| || j}|||fS t|d }d }| jr|t|kr|d }|dd  }| |}	| |	}
| | j}| ||
\}}
| |
}
| |
|	||\}}|||
fS )NFr   rT   )
_get_linesr   r  r   r  rD   r$  r`  rn   r  rw   r%  r  rh  r   _rows_to_cols_exclude_implicit_indexr   rO  _convert_datar,  )r   rowscontentr   rI   r   r   Zcount_empty_content_valsr+  r*  rb   r?   r?   r@   r]   R	  s6    





zPythonParser.readc             C   sz   |  | j}| jrb| j}i }d}xTt|D ]2\}}x|| |krJ|d7 }q4W |||  ||< q*W ndd t||D }|S )Nr   rT   c             S   s   i | ]\}}||qS r?   r?   )r   rZ  r^  r?   r?   r@   r_  	  s    z8PythonParser._exclude_implicit_index.<locals>.<dictcomp>)r$  r  r0  rn   r   r   )r   r*  rI   Zexcl_indicesrb   offsetr   r   r?   r?   r@   r  z	  s    z$PythonParser._exclude_implicit_indexc             C   s   |d kr| j }| j|dS )N)r  )rS   r]   )r   r   r?   r?   r@   r   	  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	||S )Nc                sF   i }x<t | D ].\}}t|tr6| jkr6 j| }|||< qW |S )zconverts col numbers to names)r   r   rZ   r;   r  )mappingZcleanr   r^  )r   r?   r@   _clean_mapping	  s    
z2PythonParser._convert_data.<locals>._clean_mapping)
rv   rZ   rw   r   rr   r   r;   r  rE  r~   )
r   rb   r  Z
clean_convZclean_dtypesZclean_na_valuesZclean_na_fvaluesr   Zna_valueZ	na_fvaluer?   )r   r@   r  	  s(    	




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 ]R\}}	y$ 
 }
x j|	kr  }
qW W n tk
r:    j|	k rtd|	 jd f |r|	dkr|r   |d gt|d   |||fS  j s(td j d d  }
Y nX g g }xbt	|
D ]V\}}|dkr|rvd	j||d
}ndj|d}|| | n
| qNW |s& jr&tt}xt	D ]X\}}|| }x0|dkr|d ||< d||f }|| }qW ||< |d ||< qW nr|r|	|d krt} jd k	rXt jnd}t|}||kr|| |krd}d g|  jd g _| |fdd|D  t|dkrzt}qzW |r   |d k	rz jd k	r
t|t jks, jd kr4t|t|d kr4tdt|dkrJtd jd k	rd || nd  _t|}|g}n ||d }n y 
 }
W n0 tk
r   |std|d d  }
Y nX t|
}|}|s jr  fddt|D g}n
t|g} ||d }nr jd ks6t||krN |g|}t|}n@t  jsvt|t jkrvtd |g| |g}|}|||fS )Nr   TrT   r  Fz*Passed header=%s but only %d lines in filezNo columns to parse from filer   zUnnamed: {i}_level_{level})r   levelzUnnamed: {i})r   z%s.%dc                s   h | ]} | qS r?   r?   )r   r   )this_columnsr?   r@   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 | ]}d  j |f qS )z%s%d)ro   )r   r   )r   r?   r@   r   D
  s   z/PythonParser._infer_columns.<locals>.<listcomp>)!rI   rE   rm   rZ   r   r   r   r   rD   r   _buffered_linerl  
_next_liner   r<   _clear_bufferr   r   r:   r   r   r;   rn   rj  r   r}   r   _handle_usecolsrp  ro   r   r   r   )r   rI   rr  Zclear_bufferr  rm   Zhave_mi_columnsr   r  Zhrr  Zthis_unnamed_colsr   r   r:  r"  r   r#  Zlcr   Zunnamed_countZncolsr?   )r   r  r@   rq  	  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 |	| W q tk
r   t
| j | Y qX qV | 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)rZ   r   )r   r   r?   r?   r@   r   d
  s    z/PythonParser._handle_usecols.<locals>.<genexpr>rT   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 r?   r?   )r   r   r  )col_indicesr?   r@   r   u
  s    z;PythonParser._handle_usecols.<locals>.<listcomp>.<listcomp>)r   )r   r=  )r  r?   r@   r   u
  s   z0PythonParser._handle_usecols.<locals>.<listcomp>)r}   r   r   anyrD   r<   rZ   r   r   r   r   rp  )r   r   Zusecols_keyr   r?   )r  r@   r  [
  s&    



zPythonParser._handle_usecolsc             C   s$   t | jdkr| jd S |  S dS )zH
        Return a line from buffer, filling buffer if required.
        r   N)rD   rj  r  )r   r?   r?   r@   r  z
  s    
zPythonParser._buffered_linec             C   s  |s|S t |d tjs|S |d s(|S |d d }tjrft |tsfyt|}W n tk
rd   |S X |tkrr|S |d }t|dkr|d | j	krd}|d }|dd 
|d }||| }t||d kr|||d d 7 }|g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   rT   r   Nr   )rZ   r   r   r~  r  r   r   _BOMrD   rh   r   )r   Z	first_rowZ	first_eltstartZquoteendnew_rowr?   r?   r@   _check_for_bom
  s4    
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 )Nr?   )r   r  r?   r?   r@   r   
  s    z.PythonParser._is_line_empty.<locals>.<genexpr>)r   )r   r  r?   r?   r@   _is_line_empty
  s    zPythonParser._is_line_emptyc             C   s  t | jtrx| | jr*|  jd7  _qW xyn| | j| j gd }|  jd7  _| jsz| | j| jd  sv|rzP n | jr| |g}|r|d }P W q. t	k
r   t
Y q.X q.W nx(| | jr|  jd7  _t| j qW xt| j| jd d}|  jd7  _|d k	r| |gd }| jrF| |g}|rX|d }P q| |sV|rP qW | jdkrr| |}|  jd7  _| j| |S )NrT   r   )row_num)rZ   rb   r   rm  rk  r  r   r  _remove_empty_lines
IndexErrorr   r   _next_iter_liner  rl  rj  r   )r   r  r   Z	orig_liner?   r?   r@   r  
  sL    
zPythonParser._next_linec             C   s:   | j rt|n&| jr6dj|d}t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 {row_num}: )r  r{  N)r   r   r   r:   r   stderrwrite)r   r>   r  baser?   r?   r@   _alert_malformed  s
    
zPythonParser._alert_malformedc          
   C   sz   y
t | jS  tjk
rt } zJ| js*| jrdt|}d|kr>d}| jdkrXd}|d| 7 }| || dS d}~X Y 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 bytezNULL 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   rb   r   Errorr   r   r   rq   r  )r   r  er>   r   r?   r?   r@   r    s    

zPythonParser._next_iter_linec             C   s   | j d kr|S g }xv|D ]n}g }xZ|D ]R}t|tjr@| j |krL|| q&|d || j  }t|dkrv|| P q&W || qW |S )Nr   )ry   rZ   r   r   r   findrD   )r   linesr   lrlr  r?   r?   r@   r  <  s    




zPythonParser._check_commentsc             C   sT   g }xJ|D ]B}t |dksBt |dkr
t|d tjrB|d  r
|| 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.
        rT   r   )rD   rZ   r   r   r  r   )r   r  r   r  r?   r?   r@   r  N  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  r?   r?   r@   _check_thousandsg  s
    
zPythonParser._check_thousandsc       	      C   s   g }x|D ]z}g }xft |D ]Z\}}t|tjrX||ksX| jrH|| jksX| j| rd|| q||	|| qW || q
W |S )N)
r   rZ   r   r   ru  rw  r  r  r   r  )	r   r  r  r  r   r  r  r   r  r?   r?   r@   r  o  s    

z(PythonParser._search_replace_num_columnsc             C   s$   | j td kr|S | j|| j ddS )Nrz   .)r  r  r  )rz   r   r  )r   r  r?   r?   r@   _check_decimal  s
    zPythonParser._check_decimalc             C   s
   g | _ d S )N)rj  )r   r?   r?   r@   r    s    zPythonParser._clear_bufferFc       	      C   sD  t |}t |}y|  }W n tk
r4   d}Y nX y|  }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|| _| jdd | _xt|D ]}|	d| qW t |}t|| _|||fS |dkr"d| _
| jdkr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   FrT   T)r   r  r   rn   rD   rr  r   rj  r.  insertr0  r  r  )	r   r   r  r  Z	next_lineZimplicit_first_colsr   Z
index_nameZcolumns_r?   r?   r@   rs    s>    






zPythonParser._get_index_namec                s   j } jr|t j7 }tdd |D }||krB jdk	rB jd krB jrZ jnd}g }t|}t|}g }x`|D ]X\}}	t|	}
|
|krʈ js j	rԈ j
|| |  }|||
f  jrP q|||	 q|W xh|D ]`\}}
d||d |
f } jr.t jdkr. jtjkr.d}|d| 7 } ||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)rD   )r   rowr?   r?   r@   r     s    z-PythonParser._rows_to_cols.<locals>.<genexpr>Fr   z%Expected %d fields in line %d, saw %drT   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 r?   )rD   rn   rp  )r   r   a)r   r?   r@   r     s    z.PythonParser._rows_to_cols.<locals>.<listcomp>c                s   g | ]\}}| j kr|qS r?   )rp  )r   r   r  )r   r?   r@   r     s    )rr  r0  rD   rn   maxr}   rq   r   r   r   rk  r   rf   ri   r   Z
QUOTE_NONEr  r   r  Zto_object_arrayT)r   r  Zcol_lenmax_lenZfootersZ	bad_linesZiter_contentZcontent_lenr   r  Z
actual_lenr  r>   r   Zzipped_contentr?   )r   r@   r    sJ    
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 }|	| | _ng }y||d k	r,x"t
|D ]}|t j qW |	| n>d}x8 j j| d d}|d7 }|d k	r2|| q2W W nN tk
r    jr fddt|D }|	| t|dkr Y nX   jt|7  _g  _ n|} jr|d  j  } |} jr |} |} |S )Nc                s$   g | ]\}}  | j s|qS r?   )rm  rk  )r   r   r  )r   r?   r@   r   &  s    z+PythonParser._get_lines.<locals>.<listcomp>r   rT   )r  c                s$   g | ]\}}  | j s|qS r?   )rm  rk  )r   r   r  )r   r?   r@   r   @  s    )rj  rD   rZ   rb   r   rk  r   rp   r   rn  r   r   r   r  rq   r  r   r  r  r  )r   r  r  r   Znew_posrL   r  r?   )r   r@   r    s`    "








zPythonParser._get_lines)N)N)N)r   r   r   r   rt  ro  r]   r  r   r  rq  r  r  r  r  r  r  r  r  r  r  r  r  r  r0  rs  r  r  r?   r?   r?   r@   r   s  s4   t$E
(
( #	=4$@?r   c                s    fdd}|S )Nc                 s    d krRt | }ytjt|d dddS  tk
rN   ttj|dS X n~y*tj |  dd}t|tjrzt	d|S  t	k
r   ytjtjt |  dddS  t	k
r   t
 f|  S X Y nX d S )NFignore)ZutcZboxr|   errorsr   )r|   )r  zscalar parser)ra   r|   )_concat_date_colstoolsZto_datetimer   r<   r   r&  rZ   datetimerI  r6   )	date_colsZstrsr   )rP   r|   r   r?   r@   	converterW  s8    
z'_make_date_converter.<locals>.converterr?   )rP   r|   r   r  r?   )rP   r|   r   r@   r  U  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| ||	|< || |	| qRW njt|t
rHx\t|D ]N\}}|| krtd| t||| |
\}}}||	|< || |	| qW | 	|	 || |sx&t |D ]}| | || qlW | |fS )Nc                s$   t  tr|  kp"t to"| kS )N)rZ   r   )colspec)rn   r  r?   r@   _isindex~  s    

z*_process_date_conversion.<locals>._isindexz"New date column already in dict %szDate column %s already in dict)r   rE   rZ   r[   r   r;   _try_convert_datesr<   r   r   r   r   r   rn  r   r4  )	data_dictr  Z
parse_specrn   r  r   r{   r  Znew_colsZnew_datar  r  r  new_namer   Z	old_namesrL   r   r?   )rn   r  r@   rN  {  sR    







rN  c       
         s   t |}g }xL|D ]D}||kr*|| qt|trL||krL|||  q|| qW ddd |D } fdd|D }| | }	||	|fS )NrL   c             s   s   | ]}t |V  qd S )N)r   )r   r  r?   r?   r@   r     s    z%_try_convert_dates.<locals>.<genexpr>c                s   g | ]}| kr | qS r?   r?   )r   r   )r  r?   r@   r     s    z&_try_convert_dates.<locals>.<listcomp>)rE   r   rZ   r;   r   )
ra   r  r  r   colsetcolnamesr   r  Zto_parseZnew_colr?   )r  r@   r    s    
r  c             C   s   | d kr |rt } nt } t }nt| tr|  }i } x<t|D ].\}}t|sX|g}|rht|t B }|| |< qBW dd |  D }n*t| s| g} t	| } |r| t B } t
| }| |fS )Nc             S   s   i | ]\}}t ||qS r?   )_floatify_na_values)r   rZ  r^  r?   r?   r@   r_    s    z$_clean_na_values.<locals>.<dictcomp>)r-   rE   rZ   r   r   r   r   r   rc  _stringify_na_valuesr  )rr   rs   r   Zold_na_valuesrZ  r^  r?   r?   r@   r     s,    
r   c       	      C   s   t |sd | |fS t| } t| }g }t|}xzt|D ]n\}}t|tjr|| xNt|D ]$\}}||kr`|||< | | P q`W q8|| }| | || q8W x0t|D ]$\}}t|tjr||krd ||< qW || |fS )N)r   r   r   rZ   r   r   r   r4  )	r   rn   r  Zcp_colsr  r   r   r  r8   r?   r?   r@   r    s*    



r  c                s   t | } tts.ptj t fddnH }tdd x2t|D ]$\}}t	|rf| | n|}||< qNW |d ks|dks|d krt
g }nJfdd|D }	t|	|d}|  x"t|D ]\}
}| ||
  qW fdd	| D }|| |fS )
Nc                  s    S )Nr?   r?   )default_dtyper?   r@   r]    s    z!_get_empty_meta.<locals>.<lambda>c               S   s   t jS )N)r   objectr?   r?   r?   r@   r]  !  s    Fc                s   g | ]}t g  | d qS ))rw   )r+   )r   r8   )rw   r?   r@   r   4  s    z#_get_empty_meta.<locals>.<listcomp>)rI   c                s   i | ]}t g  | d |qS ))rw   )r+   )r   r:  )rw   r?   r@   r_  ;  s   z#_get_empty_meta.<locals>.<dictcomp>)r   rZ   r   r   r  r   r   r   r   r   r'   r*   rY  r   r   )r   rn   r  rw   Z_dtyperZ  r^  r   r   rb   r   r  r   r?   )r  rw   r@   r`    s&    



r`  c             C   sT   t  }xH| D ]@}y t|}t|s.|| W q tttfk
rJ   Y qX qW |S )N)rE   floatr   Zisnanry  r   r<   OverflowError)rr   r   r^  r?   r?   r@   r  A  s    


r  c             C   s   g }x| D ]}| t| | | yFt|}|t|kr`t|}| d|  | t| | | W n tttfk
r   Y nX y| 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%s.0)r   r   r  r;   r   r<   r  rE   )rr   r   r  r^  r?   r?   r@   r  N  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)rZ   r   r-   rE   )r   rr   r   rs   r?   r?   r@   r5  g  s    

r5  c             C   sJ   t |}g }x8| D ]0}||kr*|| qt|tr|||  qW |S )N)rE   r   rZ   r;   )r  r   r  r  r   r?   r?   r@   _get_col_names  s    

r  c             C   sj   t | dkrJtjr.tjdd | d D tdS tjdd | d D tdS tjdd t|  D td}|S )NrT   c             S   s   g | ]}t |qS r?   )r   r   )r   r  r?   r?   r@   r     s    z%_concat_date_cols.<locals>.<listcomp>r   )rw   c             S   s$   g | ]}t |tjst|n|qS r?   )rZ   r   r   r   )r   r  r?   r?   r@   r     s   c             S   s    g | ]}d  dd |D qS ) c             s   s   | ]}t |V  qd S )N)r   r   )r   yr?   r?   r@   r     s    z/_concat_date_cols.<locals>.<listcomp>.<genexpr>)r   )r   r  r?   r?   r@   r     s   )rD   r   r   r   Zarrayr  r   )r  Zrsr?   r?   r@   r    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sft	dt
|j xd| jD ]Z}t|ttfrt|dkrt|d ttjt
d frt|d ttjt
d fsnt	d	qnW d S )
Nz
z
	 rO   )r   rp   z=column specifications must be a list or tuple, input was a %rr   r   rT   zEEach column specification must be 2 element tuple or list of integers)r   bufferrf   ry   detect_colspecsr   rZ   r   r   r   r   r   rD   r;   r   r  )r   r   r   rf   ry   rp   r   r  r?   r?   r@   r     s"    zFixedWidthReader.__init__c             C   sf   |dkrt  }g }g }x@t| jD ]2\}}||kr<|| || 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)rE   r   r   r   rD   iterr  )r   r   rp   Zbuffer_rowsZdetect_rowsr   r  r?   r?   r@   get_rows  s    


zFixedWidthReader.get_rowsc                s   d dd  jD }td| } ||}|s<tdttt|}t	j
|d td} jd k	rx fdd	|D }x4|D ],}x&||D ]}	d||	 |	 < qW q~W t	|d}
d
|
d
< t	||
A dkd
 }tt|d d d |dd d }|S )Nr   c             s   s   | ]}d | V  qdS )z\%sNr?   )r   r  r?   r?   r@   r     s    z3FixedWidthReader.detect_colspecs.<locals>.<genexpr>z([^%s]+)z(No rows from which to infer column widthrT   )rw   c                s   g | ]}|  jd  qS )r   )	partitionry   )r   r  )r   r?   r@   r     s    z4FixedWidthReader.detect_colspecs.<locals>.<listcomp>r   r   )r   rf   rW   rv  r  r   r  r
   rD   r   Zzerosr;   ry   finditerr  r  Zrollwherer   r   )r   r   rp   Z
delimiterspatternr  r  rC  r  mZshiftedZedgesZ
edge_pairsr?   )r   r@   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qS r?   )r  rf   )r   Zfrommto)r  r   r?   r@   r     s   z-FixedWidthReader.__next__.<locals>.<listcomp>)r  r   r   r   r   )r   r?   )r  r   r@   r     s    

zFixedWidthReader.__next__)Nr   )N)r   N)r   r   r   r   r   r  r  r   r?   r?   r?   r@   r    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,   | d| _| d| _tj| |f| d S )Nr   r   )r   r   r   r   r   )r   r   r`   r?   r?   r@   r     s    zFixedWidthFieldParser.__init__c             C   s"   t || j| j| j| j| j| _d S )N)r  r   rf   ry   rp   r   rb   )r   r   r?   r?   r@   ro    s    z"FixedWidthFieldParser._make_readerN)r   r   r   r   r   ro  r?   r?   r?   r@   r     s   r   )r   )r   )rO   Nr   )NFF)F)T)N)r   Z
__future__r   collectionsr   r   r  rW   r   textwrapr   rF   Znumpyr   Zpandas._libs.libZ_libsr  Zpandas._libs.opsZopsrK  Zpandas._libs.parsersrJ  Zpandas._libs.tslibsr   Zpandas.compatr   r   r   r   r	   r
   r   r   r   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!   Zpandas.core.dtypes.dtypesr"   Zpandas.core.dtypes.missingr#   Zpandas.corer$   Zpandas.core.arraysr%   Zpandas.core.framer&   Zpandas.core.indexr'   r(   r)   r*   Zpandas.core.seriesr+   Zpandas.core.toolsr,   r  Zpandas.io.commonr-   r.   r/   r0   r1   r2   r3   r4   r5   Zpandas.io.date_convertersr6   r  r   r/  Z_doc_read_csv_and_tablerA   rJ   rc   r   r   r   r   r   r   r   r   r   r   r:   r   r   r\   r   r   r   r   r   r  r	  r  r
  r   rg  rh  r   r  rN  r  r   r  r`  r  r  r5  r  r  r  r   r?   r?   r?   r@   <module>   s$  ,<,t /
.
 6 
M  t 7   ^  :       i 
'
>
%!
-$e