作为常用的函数,pandas.read_csv() 用于读取各种数据文件(.dat.txt.csv等),在这里做一个详细的解释。

灵活运用index_col与header准确的读取csv文件的行索引与列名

举两个例子:

读取这种没有列名行索引的文件,代码为:pandas.read_csv('data.csv', header = None),因为index_col默认为None,所以不必设置。
代码也可以为pandas.read_csv('data.csv', header = None, index_col = None)

在这里插入图片描述
读取这种有行索引列名的文件,代码为:pandas.read_csv('data.csv', index_col = 0),因为header默认值为’infer‘,在不传入names参数时默认为读取第一行为列名。
代码也可以为pandas.read_csv('data.csv', header = 0, index_col = 0)

在这里插入图片描述
介于这两者之间的情况也可以以此类推,只要改变index_col与header参数值即可。

下面先看官方网站的函数解释,本文已对所有的参数进行了解释。

需要的请看官网https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

pandas.read_csv(filepath_or_buffer, sep=<object object>, delimiter=None, header='infer', names=None, index_col=None, usecols=None, 
squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=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='.', 
lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, 
error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, 
storage_options=None)

以下格式为:参数,数据类型,默认值

filepath_or_bufferstr, path object or file-like object,在这里输入需要读入文件的名称字符串形式即可,例如:'Data.csv'

sep, str, default ‘,’,设置读取数据的间隔符号。

delimiter, str, default None,sep的备选项。

header, int, list of int, default ‘infer’参数,默认为header = 0,表示其会自动读取数据第一行为列名,如果不想读取第一行可设置header = None,如果列名被显式传递则不再自动读取列名。程序自动推断有无header传入是否读取第一行,因此默认值为'infer'

names, array-like, optional参数,用于传入列名,数据形式可以为列表。

index_col, int, str, sequence of int / str, or False, default None参数,用于设置行序号,同header一样,当index_col = 0时,则读取第一列为行序号,不需要则设置index_col = None

usecols, list-like or callable, optional参数返回一个数据子集,该列表中的值必须可以对应到文件中的位置行序号或者列名。例如:usecols有效参数可能是 [0,1,2]或者是 [‘foo’, ‘bar’, ‘baz’]。使用这个参数可以加快加载速度并降低内存消耗。

squeeze, bool, default False参数,是否当只有一列数据时返回Series,而非DataFrame

prefix, str, optional,在没有列标题时,给列序号添加前缀。例如:添加‘X’ 成为 X0, X1, …

mangle_dupe_cols, bool, default True,重复的列名会被定义为 ‘X’, ‘X.1’, …’X.N’, 而不是 ‘X’…’X’. 如果为False会导致重复的列名的数据被覆盖。

dtype, Type name or dict of column -> type, optional,列的数据类型设置,E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} 。

engine, {‘c’, ‘python’}, optional,使用的解析引擎,C更快,Python功能更全。

converters, dict, optional,将字典的值转换到确定的列,字典的键可以为整数或者列名。

true_values, list, optional ,被认为是True的值。

false_values, list, optional ,被认为是False的值。

skipinitialspace, bool, default False ,跳过定界符后的空格。.

skiprows, list-like, int or callable, optional,要跳过的行号(0索引)或文件开头要跳过的行数(int)。

skipfooter, int, default 0,文件底部需要跳过的行数。 (Unsupported with engine=’c’).

nrows, int, optional,文件中需要读取的行数。 Useful for reading pieces of large files.

na_values, scalar, str, list-like, or dict, optional,字符会被认为NaN,如果传入字典则按列替换为NaN,字典的键为列名。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’, ‘’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’.

keep_default_na, bool, default True,四种模式。

  1. 当该参数为True,且传入na_values参数,则使用默认参数与na_values参数解析。
  2. 当该参数为True,未传入na_values,则还是使用默认的NaN参数解析。
  3. 当该参数为False时,且传入na_values参数,则使用na_values参数解析。
  4. 当该参数为False,且未传入na_values参数,则没有值会被认作NaN。

na_filter, bool, default True,检测确失的值的标记,空字符串或者是na_values中定义的值。当数据中不包含空值,设置False可以提高读入大文件性能。

verbose, bool, default False,显示非数值列NA值的数目。

skip_blank_lines, bool, default True,跳过空行,而不是将空行都读作NaN值。

parse_dates, bool or list of int or names or list of lists or dict, default False
当为布尔值True时,解析索引,当为名称或者整型列表时,将其看作分离的日期列进行解析。
当为嵌套列表时,e.g. [[1, 3]] 将列1和3合并看作一个日期列。
当为字典时,e.g. {‘foo’ : [1, 3]} ,解析列1,3作为日期,结果为’foo’。
如果列或者索引不能被看作日期序列,称为不可解析的值,则将其按照原数据类型返回。
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 pandas.to_datetime() with utc=True. See Parsing a CSV with mixed timezones for more.
Note: A fast-path exists for iso8601-formatted dates.

infer_datetime_format, bool, default False,如果该参数为True且parse_dates被使用,pandas会自动推断日期数据的类型在其列中,将其转换为更快的解析日期的方式。某些情况下可以增加5到10倍解析速度。

keep_date_col, bool, default False,当该参数为True且parse_dates指定合并多列,则保留原始列。

date_parser, function, optional,设置将字符串类型的列转换为日期序列的函数。默认是使用dateutil.parser.parser做转换,
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 格式的日期,国际和欧洲的日期格式。

cache_dates, bool, default True,如果为True则指定唯一的Cache缓存用于转换日期,当处理重复的日期字符串,特别是带有时区偏移的可以显著提高速度。New in version 0.25.0.

iterator, bool, default False,返回 TextFileReader 对象用作迭代或者获取chunks通过get_chunk().
Changed in version 1.2: TextFileReader is a context manager.

chunksize, int, optional,返回用于迭代的 TextFileReader 对象. See the IO Tools docs for more information on iterator and chunksize.
Changed in version 1.2: TextFileReader is a context manager.
.
compression, {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’,用于文件的实时解压缩,如果为 ‘infer’ 和 filepath_or_buffer,则从以下拓展名中检测压缩‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (其他不解压),如果使用’zip’类型的文件,则其中只能包含一个数据文件。该参数设置为None表示不解压。

thousands, str, optional,千位分隔符,Thousands separator.

decimal, str, default ‘.’,需要被识别为小数点的字符(e.g. use ‘,’ for European data).

lineterminator, str (length 1), optional, 将文件分割为多行的字符,只有C解析器有效。

quotechar, str (length 1), optional, 用于表示引用项的开始和结束的字符。引用的项可以包含分隔符,但它将被忽略。通常为引号。

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,当定义引用符且quoting 参数不是 QUOTE_NONE时,指定是否将两个连续的引用符解释为一个引用符。

escapechar, str (length 1), optional,用于转义其他字符的字符。

comment, str, optional,表示其后面的行不被解析,如果在行的开头,则该行被忽略,参数必须为单独的字符。完全注释的行会被头参数忽略,但是不会被skiprow忽略。
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.其中\n为换行符。

encoding, str, optional,用于读取或者写入例如 utf-8 文件的UTF编码。
When encoding is None, errors=“replace” is passed to open(). Otherwise, errors=“strict” is passed to open(). This behavior was previously only the case for engine=“python”.

dialect, str or csv.Dialect, optional,如果被提供,该参数将覆盖以下参数的值,delimiter, doublequote, escapechar, skipinitialspace, quotechar, and quoting.
If it is necessary to override values, a ParserWarning will be issued. See csv.Dialect documentation for more details.

error_bad_lines, bool, default True,字段太多的行(例如csv文件行中包含太多的逗号)默认会引起中断,并且不会返回DataFrame,如果为False,这些坏行会被DataFrame中移除。

warn_bad_lines, bool, default True,If error_bad_lines is False, and warn_bad_lines is True, 每个坏行的警告都会被输出。

delim_whitespace, bool, default False,指定是否有空格(e.g. ’ ’ or ’ ‘)被用作sep。相当于设置sep=’\s+’。如果将此选项设置为True,则不应该为分隔符参数传入任何参数。

low_memory, bool, default True,在内部以块的形式处理文件,从而在解析时减少内存使用,但可能是混合类型推断。要确保没有混合类型,要么设置为False,要么使用dtype参数指定类型。请注意,无论如何整个文件都被读入一个DataFrame,使用chunksize或iterator参数以块的形式返回数据。(仅对C解析器有效)。

memory_map, bool, default False,当文件路径被提供后,将文件直接映射到内存中直接读取,该选项可以提高性能,因为不再有I/O开销。

float_precision, str, optional,指定C引擎用什么转换器处理浮点值,选项有 None or ‘high’ 对于普通转换器, ‘legacy’ 原始的pandas低精度转换器, 和 ‘round_trip’ round-trip 转换器.
Changed in version 1.2.

storage_options, dict, optional,对于特殊存储连接有意义的额外选项,例如,如果使用由fsspec解析的URL,例如启动“s3://”, “gcs://”,则使用主机、端口、用户名、密码等。如果为此参数提供 non-fsspec URL,将引发错误。See the fsspec and backend storage implementation docs for the set of allowed keys and values.
New in version 1.2.

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

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐