R(read_系列2): Function36~45
Types['Function'][35:45] ['read_parquet', 'read_pickle', 'read_sas', 'read_spss', 'read_sql', 'read_sql_query', 'read_sql_table', 'read_stata', 'read_table', 'read_xml']
Function36 read_parquet()
Help on function read_parquet in module pandas.io.parquet: read_parquet(path, engine: 'str' = 'auto', columns=None, storage_options: 'StorageOptions' = None, use_nullable_dtypes: 'bool' = False, **kwargs) Load a parquet object from the file path, returning a DataFrame. Parameters ---------- path : 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.parquet``. A file URL can also be a path to a directory that contains multiple partitioned parquet files. Both pyarrow and fastparquet support paths to directories as well as file URLs. A directory path could be: ``file://localhost/path/to/tables`` or ``s3://bucket/partition_dir`` If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. engine : {'auto', 'pyarrow', 'fastparquet'}, default 'auto' Parquet library to use. If 'auto', then the option ``io.parquet.engine`` is used. The default ``io.parquet.engine`` behavior is to try 'pyarrow', falling back to 'fastparquet' if 'pyarrow' is unavailable. columns : list, default=None If not None, only these columns will be read from the file. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details. .. versionadded:: 1.3.0 use_nullable_dtypes : bool, default False If True, use dtypes that use ``pd.NA`` as missing value indicator for the resulting DataFrame. (only applicable for the ``pyarrow`` engine) As new dtypes are added that support ``pd.NA`` in the future, the output with this option will change to use those dtypes. Note: this is an experimental option, and behaviour (e.g. additional support dtypes) may change without notice. .. versionadded:: 1.2.0 **kwargs Any additional kwargs are passed to the engine. Returns ------- DataFrame
Function37 read_pickle()
Help on function read_pickle in module pandas.io.pickle: read_pickle(filepath_or_buffer: Union[ForwardRef('PathLike[str]'), str, IO[~AnyStr], io.RawIOBase, io.BufferedIOBase, io.TextIOBase, _io.TextIOWrapper, mmap.mmap], compression: Union[str, Dict[str, Any], NoneType] = 'infer', storage_options: Union[Dict[str, Any], NoneType] = None) Load pickled pandas object (or any object) from file. .. warning:: Loading pickled data received from untrusted sources can be unsafe. See `here <https://docs.python.org/3/library/pickle.html>`__. Parameters ---------- filepath_or_buffer : str, path object or file-like object File path, URL, or buffer where the pickled object will be loaded from. .. versionchanged:: 1.0.0 Accept URL. URL is not limited to S3 and GCS. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' If 'infer' and 'path_or_url' is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression) If 'infer' and 'path_or_url' is not path-like, then use None (= no decompression). storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details. .. versionadded:: 1.2.0 Returns ------- unpickled : same type as object stored in file See Also -------- DataFrame.to_pickle : Pickle (serialize) DataFrame object to file. Series.to_pickle : Pickle (serialize) Series object to file. read_hdf : Read HDF5 file into a DataFrame. read_sql : Read SQL query or database table into a DataFrame. read_parquet : Load a parquet object, returning a DataFrame. Notes ----- read_pickle is only guaranteed to be backwards compatible to pandas 0.20.3. Examples -------- >>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)}) >>> original_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> pd.to_pickle(original_df, "./dummy.pkl") >>> unpickled_df = pd.read_pickle("./dummy.pkl") >>> unpickled_df foo bar 0 0 5 1 1 6 2 2 7 3 3 8 4 4 9 >>> import os >>> os.remove("./dummy.pkl")
Function38 read_sas()
Help on function read_sas in module pandas.io.sas.sasreader: read_sas(filepath_or_buffer: 'FilePathOrBuffer', format: 'str | None' = None, index: 'Hashable | None' = None, encoding: 'str | None' = None, chunksize: 'int | None' = None, iterator: 'bool' = False) -> 'DataFrame | ReaderBase' Read SAS files stored as either XPORT or SAS7BDAT format files. 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.sas``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. format : str {'xport', 'sas7bdat'} or None If None, file format is inferred from file extension. If 'xport' or 'sas7bdat', uses the corresponding format. index : identifier of index column, defaults to None Identifier of column that should be used as index of the DataFrame. encoding : str, default is None Encoding for text data. If None, text data are stored as raw bytes. chunksize : int Read file `chunksize` lines at a time, returns iterator. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. iterator : bool, defaults to False If True, returns an iterator for reading the file incrementally. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. Returns ------- DataFrame if iterator=False and chunksize=None, else SAS7BDATReader or XportReader
Function39 read_spss()
Help on function read_spss in module pandas.io.spss: read_spss(path: 'str | Path', usecols: 'Sequence[str] | None' = None, convert_categoricals: 'bool' = True) -> 'DataFrame' Load an SPSS file from the file path, returning a DataFrame. .. versionadded:: 0.25.0 Parameters ---------- path : str or Path File path. usecols : list-like, optional Return a subset of the columns. If None, return all columns. convert_categoricals : bool, default is True Convert categorical columns into pd.Categorical. Returns ------- DataFrame
Function40 read_sql()
Help on function read_sql in module pandas.io.sql: read_sql(sql, con, index_col: 'str | Sequence[str] | None' = None, coerce_float: 'bool' = True, params=None, parse_dates=None, columns=None, chunksize: 'int | None' = None) -> 'DataFrame | Iterator[DataFrame]' Read SQL query or database table into a DataFrame. This function is a convenience wrapper around ``read_sql_table`` and ``read_sql_query`` (for backward compatibility). It will delegate to the specific function depending on the provided input. A SQL query will be routed to ``read_sql_query``, while a database table name will be routed to ``read_sql_table``. Note that the delegated function might have more specific notes about their functionality not listed here. Parameters ---------- sql : str or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con : SQLAlchemy connectable, str, or sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically. See `here <https://docs.sqlalchemy.org/en/13/core/connections.html>`_. index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns : list, default: None List of column names to select from SQL table (only used when reading a table). chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame or Iterator[DataFrame] See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql_query : Read SQL query into a DataFrame. Examples -------- Read data from SQL via either a SQL query or a SQL tablename. When using a SQLite database only SQL queries are accepted, providing only the SQL tablename will result in an error. >>> from sqlite3 import connect >>> conn = connect(':memory:') >>> df = pd.DataFrame(data=[[0, '10/11/12'], [1, '12/11/10']], ... columns=['int_column', 'date_column']) >>> df.to_sql('test_data', conn) >>> pd.read_sql('SELECT int_column, date_column FROM test_data', conn) int_column date_column 0 0 10/11/12 1 1 12/11/10 >>> pd.read_sql('test_data', 'postgres:///db_name') # doctest:+SKIP Apply date parsing to columns through the ``parse_dates`` argument >>> pd.read_sql('SELECT int_column, date_column FROM test_data', ... conn, ... parse_dates=["date_column"]) int_column date_column 0 0 2012-10-11 1 1 2010-12-11 The ``parse_dates`` argument calls ``pd.to_datetime`` on the provided columns. Custom argument values for applying ``pd.to_datetime`` on a column are specified via a dictionary format: 1. Ignore errors while parsing the values of "date_column" >>> pd.read_sql('SELECT int_column, date_column FROM test_data', ... conn, ... parse_dates={"date_column": {"errors": "ignore"}}) int_column date_column 0 0 2012-10-11 1 1 2010-12-11 2. Apply a dayfirst date parsing order on the values of "date_column" >>> pd.read_sql('SELECT int_column, date_column FROM test_data', ... conn, ... parse_dates={"date_column": {"dayfirst": True}}) int_column date_column 0 0 2012-11-10 1 1 2010-11-12 3. Apply custom formatting when date parsing the values of "date_column" >>> pd.read_sql('SELECT int_column, date_column FROM test_data', ... conn, ... parse_dates={"date_column": {"format": "%d/%m/%y"}}) int_column date_column 0 0 2012-11-10 1 1 2010-11-12
Function41 read_sql_query()
Help on function read_sql_query in module pandas.io.sql: read_sql_query(sql, con, index_col=None, coerce_float: 'bool' = True, params=None, parse_dates=None, chunksize: 'int | None' = None, dtype: 'DtypeArg | None' = None) -> 'DataFrame | Iterator[DataFrame]' Read SQL query into a DataFrame. Returns a DataFrame corresponding to the result set of the query string. Optionally provide an `index_col` parameter to use one of the columns as the index, otherwise default integer index will be used. Parameters ---------- sql : str SQL query or SQLAlchemy Selectable (select or text object) SQL query to be executed. con : SQLAlchemy connectable, str, or sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Useful for SQL result sets. params : list, tuple or dict, optional, default: None List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}. parse_dates : list or dict, default: None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. dtype : Type name or dict of columns Data type for data or columns. E.g. np.float64 or {¡®a¡¯: np.float64, ¡®b¡¯: np.int32, ¡®c¡¯: ¡®Int64¡¯} .. versionadded:: 1.3.0 Returns ------- DataFrame or Iterator[DataFrame] See Also -------- read_sql_table : Read SQL database table into a DataFrame. read_sql : Read SQL query or database table into a DataFrame. Notes ----- Any datetime values with time zone information parsed via the `parse_dates` parameter will be converted to UTC.
Function42 read_sql_table()
Help on function read_sql_table in module pandas.io.sql: read_sql_table(table_name: 'str', con, schema: 'str | None' = None, index_col: 'str | Sequence[str] | None' = None, coerce_float: 'bool' = True, parse_dates=None, columns=None, chunksize: 'int | None' = None) -> 'DataFrame | Iterator[DataFrame]' Read SQL database table into a DataFrame. Given a table name and a SQLAlchemy connectable, returns a DataFrame. This function does not support DBAPI connections. Parameters ---------- table_name : str Name of SQL table in database. con : SQLAlchemy connectable or str A database URI could be provided as str. SQLite DBAPI connection mode not supported. schema : str, default None Name of SQL schema in database to query (if database flavor supports this). Uses default schema if None (default). index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Can result in loss of Precision. parse_dates : list or dict, default None - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns : list, default None List of column names to select from SQL table. chunksize : int, default None If specified, returns an iterator where `chunksize` is the number of rows to include in each chunk. Returns ------- DataFrame or Iterator[DataFrame] A SQL table is returned as two-dimensional data structure with labeled axes. See Also -------- read_sql_query : Read SQL query into a DataFrame. read_sql : Read SQL query or database table into a DataFrame. Notes ----- Any datetime values with time zone information will be converted to UTC. Examples -------- >>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
Function43 read_stata()
Help on function read_stata in module pandas.io.stata: read_stata(filepath_or_buffer: 'FilePathOrBuffer', convert_dates: 'bool' = True, convert_categoricals: 'bool' = True, index_col: 'str | None' = None, convert_missing: 'bool' = False, preserve_dtypes: 'bool' = True, columns: 'Sequence[str] | None' = None, order_categoricals: 'bool' = True, chunksize: 'int | None' = None, iterator: 'bool' = False, compression: 'CompressionOptions' = 'infer', storage_options: 'StorageOptions' = None) -> 'DataFrame | StataReader' Read Stata file into DataFrame. Parameters ---------- filepath_or_buffer : str, path object or file-like object Any valid string path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. A local file could be: ``file://localhost/path/to/table.dta``. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. convert_dates : bool, default True Convert date variables to DataFrame time values. convert_categoricals : bool, default True Read value labels and convert columns to Categorical/Factor variables. index_col : str, optional Column to set as index. convert_missing : bool, default False Flag indicating whether to convert missing values to their Stata representations. If False, missing values are replaced with nan. If True, columns containing missing values are returned with object data types and missing values are represented by StataMissingValue objects. preserve_dtypes : bool, default True Preserve Stata datatypes. If False, numeric data are upcast to pandas default types for foreign data (float64 or int64). columns : list or None Columns to retain. Columns will be returned in the given order. None returns all columns. order_categoricals : bool, default True Flag indicating whether converted categorical data are ordered. chunksize : int, default None Return StataReader object for iterations, returns chunks with given number of lines. iterator : bool, default False Return StataReader object. compression : str or dict, default None If string, specifies compression mode. If dict, value at key 'method' specifies compression mode. Compression mode must be one of {'infer', 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no compression). If dict and compression mode is one of {'zip', 'gzip', 'bz2'}, or inferred as one of the above, other entries passed as additional compression options. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details. Returns ------- DataFrame or StataReader See Also -------- io.stata.StataReader : Low-level reader for Stata data files. DataFrame.to_stata: Export Stata data files. Notes ----- Categorical variables read through an iterator may not have the same categories and dtype. This occurs when a variable stored in a DTA file is associated to an incomplete set of value labels that only label a strict subset of the values. Examples -------- Read a Stata dta file: >>> df = pd.read_stata('filename.dta') Read a Stata dta file in 10,000 line chunks: >>> itr = pd.read_stata('filename.dta', chunksize=10000) >>> for chunk in itr: ... do_something(chunk)
Function44 read_table()
Help on function read_table in module pandas.io.parsers.readers: read_table(filepath_or_buffer: 'FilePathOrBuffer', sep=<no_default>, delimiter=None, header='infer', names=<no_default>, index_col=None, usecols=None, squeeze=False, prefix=<no_default>, mangle_dupe_cols=True, dtype: 'DtypeArg | None' = None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal: 'str' = '.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=None, warn_bad_lines=None, on_bad_lines=None, encoding_errors: 'str | None' = 'strict', delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) Read general delimited file 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, gs, and file. For file URLs, a host is expected. A local file could be: file://localhost/path/to/table.csv. If you want to pass in a path object, pandas accepts any ``os.PathLike``. By file-like object, we refer to objects with a ``read()`` method, such as a file handle (e.g. via builtin ``open`` function) or ``StringIO``. sep : str, default '\\t' (tab-stop) 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: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A', 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'. keep_default_na : bool, default True Whether or not to include the default NaN values when parsing the data. Depending on whether `na_values` is passed in, the behavior is as follows: * If `keep_default_na` is True, and `na_values` are specified, `na_values` is appended to the default NaN values used for parsing. * If `keep_default_na` is True, and `na_values` are not specified, only the default NaN values are used for parsing. * If `keep_default_na` is False, and `na_values` are specified, only the NaN values specified `na_values` are used for parsing. * If `keep_default_na` is False, and `na_values` are not specified, no strings will be parsed as NaN. Note that if `na_filter` is passed in as False, the `keep_default_na` and `na_values` parameters will be ignored. na_filter : bool, default True Detect missing value markers (empty strings and the value of na_values). In data without any NAs, passing na_filter=False can improve the performance of reading a large file. verbose : bool, default False Indicate number of NA values placed in non-numeric columns. skip_blank_lines : bool, default True If True, skip over blank lines rather than interpreting as NaN values. parse_dates : bool or list of int or names or list of lists or dict, default False The behavior is as follows: * boolean. If True -> try parsing the index. * list of int or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column. * list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column. * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result 'foo' If a column or index cannot be represented as an array of datetimes, say because of an unparsable value or a mixture of timezones, the column or index will be returned unaltered as an object data type. For non-standard datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``. To parse an index or column with a mixture of timezones, specify ``date_parser`` to be a partially-applied :func:`pandas.to_datetime` with ``utc=True``. See :ref:`io.csv.mixed_timezones` for more. Note: A fast-path exists for iso8601-formatted dates. infer_datetime_format : bool, default False If True and `parse_dates` is enabled, pandas will attempt to infer the format of the datetime strings in the columns, and if it can be inferred, switch to a faster method of parsing them. In some cases this can increase the parsing speed by 5-10x. keep_date_col : bool, default False If True and `parse_dates` specifies combining multiple columns then keep the original columns. date_parser : function, optional Function to use for converting a sequence of string columns to an array of datetime instances. The default uses ``dateutil.parser.parser`` to do the conversion. Pandas will try to call `date_parser` in three different ways, advancing to the next if an exception occurs: 1) Pass one or more arrays (as defined by `parse_dates`) as arguments; 2) concatenate (row-wise) the string values from the columns defined by `parse_dates` into a single array and pass that; and 3) call `date_parser` once for each row using one or more strings (corresponding to the columns defined by `parse_dates`) as arguments. dayfirst : bool, default False DD/MM format dates, international and European format. cache_dates : bool, default True If True, use a cache of unique, converted dates to apply the datetime conversion. May produce significant speed-up when parsing duplicate date strings, especially ones with timezone offsets. .. versionadded:: 0.25.0 iterator : bool, default False Return TextFileReader object for iteration or getting chunks with ``get_chunk()``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. .. versionchanged:: 1.2 ``TextFileReader`` is a context manager. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise no decompression). If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. thousands : str, optional Thousands separator. decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). lineterminator : str (length 1), optional Character to break file into lines. Only valid with C parser. quotechar : str (length 1), optional The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored. quoting : int or csv.QUOTE_* instance, default 0 Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3). doublequote : bool, default ``True`` When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single ``quotechar`` element. escapechar : str (length 1), optional One-character string used to escape other characters. comment : str, optional Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as ``skip_blank_lines=True``), fully commented lines are ignored by the parameter `header` but not by `skiprows`. For example, if ``comment='#'``, parsing ``#empty\na,b,c\n1,2,3`` with ``header=0`` will result in 'a,b,c' being treated as the header. encoding : str, optional Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python standard encodings <https://docs.python.org/3/library/codecs.html#standard-encodings>`_ . .. versionchanged:: 1.2 When ``encoding`` is ``None``, ``errors="replace"`` is passed to ``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``. This behavior was previously only the case for ``engine="python"``. .. versionchanged:: 1.3.0 ``encoding_errors`` is a new argument. ``encoding`` has no longer an influence on how encoding errors are handled. encoding_errors : str, optional, default "strict" How encoding errors are treated. `List of possible values <https://docs.python.org/3/library/codecs.html#error-handlers>`_ . .. versionadded:: 1.3.0 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 ``None`` 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 be dropped from the DataFrame that is returned. .. deprecated:: 1.3.0 The ``on_bad_lines`` parameter should be used instead to specify behavior upon encountering a bad line instead. warn_bad_lines : bool, default ``None`` If error_bad_lines is False, and warn_bad_lines is True, a warning for each "bad line" will be output. .. deprecated:: 1.3.0 The ``on_bad_lines`` parameter should be used instead to specify behavior upon encountering a bad line instead. on_bad_lines : {'error', 'warn', 'skip'}, default 'error' Specifies what to do upon encountering a bad line (a line with too many fields). Allowed values are : - 'error', raise an Exception when a bad line is encountered. - 'warn', raise a warning when a bad line is encountered and skip that line. - 'skip', skip bad lines without raising or warning when they are encountered. .. versionadded:: 1.3.0 delim_whitespace : bool, default False Specifies whether or not whitespace (e.g. ``' '`` or ``' '``) will be used as the sep. Equivalent to setting ``sep='\s+'``. If this option is set to True, nothing should be passed in for the ``delimiter`` parameter. low_memory : bool, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type with the `dtype` parameter. Note that the entire file is read into a single DataFrame regardless, use the `chunksize` or `iterator` parameter to return the data in chunks. (Only valid with C parser). memory_map : bool, default False If a filepath is provided for `filepath_or_buffer`, map the file object directly onto memory and access the data directly from there. Using this option can improve performance because there is no longer any I/O overhead. float_precision : str, optional Specifies which converter the C engine should use for floating-point values. The options are ``None`` or 'high' for the ordinary converter, 'legacy' for the original lower precision pandas converter, and 'round_trip' for the round-trip converter. .. versionchanged:: 1.2 storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details. .. versionadded:: 1.2 Returns ------- DataFrame or TextParser A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes. See Also -------- DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file. read_csv : Read a comma-separated values (csv) file into DataFrame. read_fwf : Read a table of fixed-width formatted lines into DataFrame. Examples -------- >>> pd.read_table('data.csv') # doctest: +SKIP
Function45 read_xml()
Help on function read_xml in module pandas.io.xml: read_xml(path_or_buffer: 'FilePathOrBuffer', xpath: 'str | None' = './*', namespaces: 'dict | list[dict] | None' = None, elems_only: 'bool | None' = False, attrs_only: 'bool | None' = False, names: 'list[str] | None' = None, encoding: 'str | None' = 'utf-8', parser: 'str | None' = 'lxml', stylesheet: 'FilePathOrBuffer | None' = None, compression: 'CompressionOptions' = 'infer', storage_options: 'StorageOptions' = None) -> 'DataFrame' Read XML document into a ``DataFrame`` object. .. versionadded:: 1.3.0 Parameters ---------- path_or_buffer : str, path object, or file-like object Any valid XML string or path is acceptable. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. xpath : str, optional, default './\*' The XPath to parse required set of nodes for migration to DataFrame. XPath should return a collection of elements and not a single element. Note: The ``etree`` parser supports limited XPath expressions. For more complex XPath, use ``lxml`` which requires installation. namespaces : dict, optional The namespaces defined in XML document as dicts with key being namespace prefix and value the URI. There is no need to include all namespaces in XML, only the ones used in ``xpath`` expression. Note: if XML document uses default namespace denoted as `xmlns='<URI>'` without a prefix, you must assign any temporary namespace prefix such as 'doc' to the URI in order to parse underlying nodes and/or attributes. For example, :: namespaces = {"doc": "https://example.com"} elems_only : bool, optional, default False Parse only the child elements at the specified ``xpath``. By default, all child elements and non-empty text nodes are returned. attrs_only : bool, optional, default False Parse only the attributes at the specified ``xpath``. By default, all attributes are returned. names : list-like, optional Column names for DataFrame of parsed XML data. Use this parameter to rename original element names and distinguish same named elements. encoding : str, optional, default 'utf-8' Encoding of XML document. parser : {'lxml','etree'}, default 'lxml' Parser module to use for retrieval of data. Only 'lxml' and 'etree' are supported. With 'lxml' more complex XPath searches and ability to use XSLT stylesheet are supported. stylesheet : str, path object or file-like object A URL, file-like object, or a raw string containing an XSLT script. This stylesheet should flatten complex, deeply nested XML documents for easier parsing. To use this feature you must have ``lxml`` module installed and specify 'lxml' as ``parser``. The ``xpath`` must reference nodes of transformed XML document generated after XSLT transformation and not the original XML document. Only XSLT 1.0 scripts and not later versions is currently supported. compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer', then use gzip, bz2, zip or xz if path_or_buffer is a string ending in '.gz', '.bz2', '.zip', or 'xz', respectively, and no decompression otherwise. If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. storage_options : dict, optional Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to ``urllib`` as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to ``fsspec``. Please see ``fsspec`` and ``urllib`` for more details. Returns ------- df A DataFrame. See Also -------- read_json : Convert a JSON string to pandas object. read_html : Read HTML tables into a list of DataFrame objects. Notes ----- This method is best designed to import shallow XML documents in following format which is the ideal fit for the two-dimensions of a ``DataFrame`` (row by column). :: <root> <row> <column1>data</column1> <column2>data</column2> <column3>data</column3> ... </row> <row> ... </row> ... </root> As a file format, XML documents can be designed any way including layout of elements and attributes as long as it conforms to W3C specifications. Therefore, this method is a convenience handler for a specific flatter design and not all possible XML structures. However, for more complex XML documents, ``stylesheet`` allows you to temporarily redesign original document with XSLT (a special purpose language) for a flatter version for migration to a DataFrame. This function will *always* return a single :class:`DataFrame` or raise exceptions due to issues with XML document, ``xpath``, or other parameters. Examples -------- >>> xml = '''<?xml version='1.0' encoding='utf-8'?> ... <data xmlns="http://example.com"> ... <row> ... <shape>square</shape> ... <degrees>360</degrees> ... <sides>4.0</sides> ... </row> ... <row> ... <shape>circle</shape> ... <degrees>360</degrees> ... <sides/> ... </row> ... <row> ... <shape>triangle</shape> ... <degrees>180</degrees> ... <sides>3.0</sides> ... </row> ... </data>''' >>> df = pd.read_xml(xml) >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0 >>> xml = '''<?xml version='1.0' encoding='utf-8'?> ... <data> ... <row shape="square" degrees="360" sides="4.0"/> ... <row shape="circle" degrees="360"/> ... <row shape="triangle" degrees="180" sides="3.0"/> ... </data>''' >>> df = pd.read_xml(xml, xpath=".//row") >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0 >>> xml = '''<?xml version='1.0' encoding='utf-8'?> ... <doc:data xmlns:doc="https://example.com"> ... <doc:row> ... <doc:shape>square</doc:shape> ... <doc:degrees>360</doc:degrees> ... <doc:sides>4.0</doc:sides> ... </doc:row> ... <doc:row> ... <doc:shape>circle</doc:shape> ... <doc:degrees>360</doc:degrees> ... <doc:sides/> ... </doc:row> ... <doc:row> ... <doc:shape>triangle</doc:shape> ... <doc:degrees>180</doc:degrees> ... <doc:sides>3.0</doc:sides> ... </doc:row> ... </doc:data>''' >>> df = pd.read_xml(xml, ... xpath="//doc:row", ... namespaces={"doc": "https://example.com"}) >>> df shape degrees sides 0 square 360 4.0 1 circle 360 NaN 2 triangle 180 3.0
日常工作中,read_系列以read_clipboard()、 read_csv()、 read_excel()这3个读取OA类数据的最为常用;另外读取网络数据(表)的3个 read_html()、read_xml()、 read_json() 也较为常用。
1. read_clipboard() 从剪贴板读取文本并传递到read_csv
2. read_csv() 将逗号分隔文本(csv)文件读入DataFrame,支持可选地将文件迭代或拆分为块。
3. read_execl() 将Excel文件读入panda DataFrame,支持文件格式:“xls”、“xlsx”、“.xlsm”、“xlsb”、“odf”、“od”和“odt”文件扩展名,可以从本地文件系统读取,也可URL读取。支持读取一个或多个工作表(WorkSheet)。
read_execl() 参数默认值:
read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype: 'DtypeArg | None' = None,engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=None, mangle_dupe_cols=True, storage_options: 'StorageOptions' = None)
参数使用说明:
1. io
读入的文件对象,支持“xls”、“xlsx”、“.xlsm”、“xlsb”等扩展名,文件名可带上全路径也可以是相对路径,也支持网络读取,如http://,https://,ftp://等,本地文件也能写成file:///形式。
>>> df = pd.read_excel('data.xlsx') >>> df = pd.read_excel(r'd:\data.xlsx') >>> df = pd.read_excel('file:///d://data.xlsx')
2. sheet_name=0
指定读入文件的工作表,sheet索引从0开始,默认第1个即=0。
【注意】也支持用worksheet的表名来赋值参数,以下2行代码一般情况下是等价的:
>>> df = pd.read_excel(r'd:\data.xlsx', sheet_name='Sheet3') >>> df = pd.read_excel(r'd:\data.xlsx', sheet_name=2)
工作表不存在或索引超范围的报错分别为:
ValueError: Worksheet named 'Sheet4' not found ValueError: Worksheet index 3 is invalid, 3 worksheets found
3. header=0
指定列表中从第几行作为表头。凡是索引一般都从0开始,以下参数同。
df = pd.read_excel(r'd:\data.xlsx', header=3)
索引号大于等于总行数报错:
ValueError: Passed header=7 but only 7 lines in file
4. names=None
参数接收一个列表,重定义赋值列名(表头),列表长度小于等于总列数。
df = pd.read_excel(r"d:\data.xlsx", names=['序号','姓名','性别','婚否','出生年月'])
参数长度大于总列数时报错:
ValueError: Number of passed names did not match number of header fields in the file
5. index_col=None
参数指定从第几列开始索引;默认值为None表示索引从0开始。
df = pd.read_excel(r"d:\data.xlsx", index_col=1)
6. usecols=None
参数指定所要读取的列,可以用字符串表示,支持切片形式但包括切片两端,如usecols="A:C"表示读取A到C列包括C列;="A,C,E:F"表示选择A列,C列、E列和F列;也可以用数字索引列表来表示,如usecols=[0,2]与="A,C"等价;还可以用表头列名列表来表示,usecols=["姓名","性别"];默认值为None表示读取所有的列。
df = pd.read_excel(r"d:\data.xlsx", usecols="A:C") df = pd.read_excel(r"d:\data.xlsx", usecols="A,C,E:F") df = pd.read_excel(r"d:\data.xlsx", usecols=[0,2]) df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","性别"])
列的字母标号不区分大小写,数字索引只能是列表不支持切片形式。
前2种用法标号不管是字母还是数字索引,超过最后的列都会抛出错误:
FutureWarning: Defining usecols with out of bounds indices is deprecated and will raise a ParserError in a future version.
第3种用法如用了表头中没存在的列名,则报错:
ValueError: Usecols do not match columns, columns expected but not found: ['奖金']
7. squeeze=False
当读取列数仅1列且squeeze=True时,返回值Series类。如下测试:
>>> df = pd.read_excel(r"d:\data.xlsx", usecols=[0,1], squeeze=True) >>> type(df) <class 'pandas.core.frame.DataFrame'> >>> df = pd.read_excel(r"d:\data.xlsx", usecols=[1], squeeze=False) >>> type(df) <class 'pandas.core.frame.DataFrame'> >>> df = pd.read_excel(r"d:\data.xlsx", usecols=[1], squeeze=True) >>> type(df) <class 'pandas.core.series.Series'>
8. dtype: 'DtypeArg | None' = None,engine=None
指定列的数据类型,也可以用字典指定某几列为某些类型。类型可用python内置类型,也可以用库numpy内置的类型。
>>> df = pd.read_excel(r"d:\data.xlsx", dtype=str) >>> type(df.基本工资[0]) <class 'str'> >>> df = pd.read_excel(r"d:\data.xlsx", dtype={"出生年月":str,"基本工资":float}) >>> type(df.基本工资[0]) <class 'numpy.float64'>
numpy数据类型众多,选择Excel支持的类型即可。
类型 备注 说明
bool8 = bool_(加下滑线代表为最大) 8位(1byte=8bits) 布尔类型
int8 = byte 8位 整型
int16 = short 16位 整型
int32 = intc 32位 整型
int_ = int64 = long = int0 = intp 64位 整型
uint8 = ubyte 8位 无符号整型
uint16 = ushort 16位 无符号整型
uint32 = uintc 32位 无符号整型
uint64 = uintp = uint0 = uint 64位 无符号整型
float16 = half 16位 浮点型
float32 = single 32位 浮点型
float_ = float64 = double 64位 浮点型
str_ = unicode_ = str0 = unicode Unicode 字符串
datetime64 日期时间类型
timedelta64 表示两个时间之间的间隔
9. engine=None
指定Excel处理引擎,一般不用设置,由pandas自己确定即可。引擎有以下四种:
- "xlrd" 支持旧版Excel文件(.xls).
- "openpyxl" 支持新版Excel文件(.xlsx, .xlsm等).
- "odf" 支持OpenDocument文件(.odf, .ods, .odt).
- "pyxlsb" 支持二进制Excel文件.
默认值为None,它由以下条件确定pandas使用何种处理引擎:
-如果“path_or_buffer”是OpenDocument格式,将使用odf<https://pypi.org/project/odfpy/>。
-如果“path_or_buffer”是xls格式,xlrd将被使用。
-如果安装了openpyxl<https://pypi.org/project/openpyxl/>,则将使用openpyxl。
-如果安装了xlrd>=2.0,将引发`ValueError`,否则将使用“xlrd”,并引发“FutureWarning”。
10. converters=None
可以和dtype一样用,但多了用函数或lambda表达式处理指定列的功能。若设置converters参数,则参数dtype失效;也有可能直接抛出错误ParserWarning: Both a converter and dtype were specified for column 某列名 - only the converter will be used。
>>> df = pd.read_excel(r"d:\data.xlsx", converters={"出生年月":int,"基本工资":str}) >>> df = pd.read_excel(r"d:\data.xlsx", converters={"出生年月":str,"基本工资":lambda x:x*1.05}) >>> df = pd.read_excel(r"d:\data.xlsx", dtype={"出生年月":int,"基本工资":str}, converters={"出生年月":str,"基本工资":lambda x:x*1.05}) Warning (from warnings module): File "D:\Python\lib\site-packages\pandas\io\excel\_base.py", line 372 data = io.parse( ParserWarning: Both a converter and dtype were specified for column 出生年月 - only the converter will be used Warning (from warnings module): File "D:\Python\lib\site-packages\pandas\io\excel\_base.py", line 372 data = io.parse( ParserWarning: Both a converter and dtype were specified for column 基本工资 - only the converter will be used >>> df = pd.read_excel(r"d:\data.xlsx", dtype={"出生年月":int,"基本工资":str}, converters={"出生年月":str,"基本工资":lambda x:x*1.05}) >>> type(df.出生年月[0]) <class 'str'> >>> type(df.基本工资[0]) <class 'numpy.float64'>
11.12. true_values=None, false_values=None
前者指定某些值为True,后者指定某些值为False。
>>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"]) >>> df.head() 姓名 婚否 0 张三 已婚 1 李四 未婚 2 王五 未婚 3 赵六 离异 4 小明 未婚 >>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"], true_values=["已婚"], false_values=["未婚","离异"]) >>> df.head() 姓名 婚否 0 张三 True 1 李四 False 2 王五 False 3 赵六 False 4 小明 False >>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"], true_values=["已婚","离异"], false_values=["未婚"]) >>> df.head() 姓名 婚否 0 张三 True 1 李四 False 2 王五 False 3 赵六 True 4 小明 False
13. skiprows=None
跳过指定的行,可以是前几行、或者列表指定某几行,也可用函数指定某些行。
注意:索引0指表头,建议不要跳过表头,跳过后的数据首行作表头不便于引用。
>>> df = pd.read_excel(r"d:\data.xlsx", skiprows=4) >>> df = pd.read_excel(r"d:\data.xlsx", skiprows=[1,3]) >>> df = pd.read_excel(r"d:\data.xlsx", skiprows=lambda i:i%2)
14. nrows=None
只读取前n行,n必须为非负整数。
df = pd.read_excel(r"d:\data.xlsx", nrows=5)
若参数被指定为负整数或者其它类型值,则报错:
ValueError: 'nrows' must be an integer >=0
15. na_values=None
指定某些值为错误值NaN。
>>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"]) >>> df.head() 姓名 婚否 0 张三 已婚 1 李四 未婚 2 王五 未婚 3 赵六 离异 4 小明 未婚 >>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"], na_values="离异") >>> df.head() 姓名 婚否 0 张三 已婚 1 李四 未婚 2 王五 未婚 3 赵六 NaN 4 小明 未婚 >>> df = pd.read_excel(r"d:\data.xlsx", usecols=["姓名","婚否"], na_values=["离异","已婚"]) >>> df.head() 姓名 婚否 0 张三 NaN 1 李四 未婚 2 王五 未婚 3 赵六 NaN 4 小明 未婚
与之相反,要替代掉DataFrame中的NaN值,则用 df.fillna("空单元格或错误值")。
16. keep_default_na=True
分析数据时是否包含默认NaN值。
根据“keep_fault_na”的布尔值,并结合看参数“na_values”是否指定会有不同效果:
*如为True,并且指定“na_values”,则“na_values”附加到用于解析的默认NaN值。
*如为True,且未指定“na_values”,则仅默认NaN值用于解析。
*如为False,并且指定“na_values”,则仅指定的NaN值“na_values”用于解析。
*如为False,且未指定“na_values”,则为否字符串将被解析为NaN。
注意:如果“na_filter”作为False传入,则“keep_fault_na”和“na_values”参数都会被忽略。
17. na_filter=True
检测丢失的值标记(空字符串和na_values的值)。
在没有任何na的数据中,传递na_filter=False可以提高读取大型文件的性能。
18. verbose=False
指示放置在非数字列中的NA值的数量。
19. parse_dates=False
处理日期类数据。
*布尔型bool,如果为True->请尝试解析索引。
*整数值索引或表头名称的列表。如[1,2,3]->尝试解析列1,2,3,每个都作为单独的日期列。
*列表的列表。如果[[1,3]]->组合列1和3并解析为单个日期列。
*字典dict,如{'fo':[1,3]}->将列1,3解析为日期和调用结果'foo'
如果列或索引包含不可分析的日期,则整个列或索引将作为对象数据类型原样返回。
如果不想将某些单元格解析为日期,只需在Excel中将其类型更改为“文本”即可。
对于非标准日期时间分析,在pd.read_excel之后使用pd.to_datetime。
20. date_parser=None
设置处理日期数据的函数。
利用lambda函数,将某个字符串列,解析为日期格式。
用于将字符串列序列转换为datetime实例数组的函数。默认值使用“dateutil.parser.parser”进行转换。Pandas将尝试以三种不同的方式调用“date_parser”,如果发生异常,则继续调用下一种:1)传递一个或多个数组(由“parse_dates”定义)作为参数;2) 将“parse_dates”定义的列中的字符串值连接(按行)到单个数组中并传递;以及3)使用一个或多个字符串(对应于“parse_dates”定义的列)作为参数,为每行调用一次“date_parser”。
21. thousands=None
用于将字符串列解析为数字的千位分隔符。请注意,此参数仅对Excel中存储为TEXT的列是必需的,无论显示格式如何,都会自动解析任何数值列。
22. comment=None
注释超出行的其余部分。向此参数传递一个或多个字符,以指示输入文件中的注释。注释字符串与当前行结尾之间的任何数据都将被忽略。
23. skipfooter=0
末尾要跳过的行数。
指定值大于等于总行数,返回一个空DataFrame。
指定负值或者其它类型,则报以下2种错误:
ValueError: skipfooter cannot be negative
ValueError: skipfooter must be an integer
24. convert_float=None
将整数浮点数转换为int(即1.0-->1)。本参数已弃用,将在将来的版本中删除。
如果为False,则所有数字数据都将作为浮点数读入:Excel将所有数字作为浮点数存储在内部。
25. mangle_dupe_cols=True
重复的列将指定为“X”、“X.1”、…“X.N”,而不是“X”…“X’。
如果列中有重复的名称,则传入False将导致数据被覆盖。
26. storage_options: 'StorageOptions' = None
如果使用将由`fsspec``解析的URL,例如开始“s3://”、“gcs://”,则对于特定存储连接有意义的额外选项,例如主机、端口、用户名、密码等。如果为该参数提供本地路径或类似文件的缓冲区,将引发错误。请参阅fsspec和后端存储实现文档,以获取一组允许的键和值。
注:第16~26号参数(第23除外),直接交给百度翻译了,暂未做代码测试。