python - 防止 pandas read_csv 将第一行视为列名的标题

标签 python pandas csv header-row

我正在使用 pd.read_csv 读取 pandas DataFrame。我想将第一行保留为数据,但它不断转换为列名。

  • 我试过 header=False 但这完全删除了它。

(注意我的输入数据:我有一个字符串 (st = '\n'.join(lst)),我将其转换为类似文件的对象 (io.StringIO (st)),然后从该文件对象构建 csv。)

最佳答案

您希望 header=NoneFalse 类型提升为 int0 参见 docs强调我的:

header : int or list of ints, default ‘infer’ Row number(s) to use as the column names, and the start of the data. Default behavior is as if set to 0 if no names passed, otherwise 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.

您可以看到行为上的差异,首先使用 header=0:

In [95]:
import io
import pandas as pd
t="""a,b,c
0,1,2
3,4,5"""
pd.read_csv(io.StringIO(t), header=0)

Out[95]:
   a  b  c
0  0  1  2
1  3  4  5

现在 None:

In [96]:
pd.read_csv(io.StringIO(t), header=None)

Out[96]:
   0  1  2
0  a  b  c
1  0  1  2
2  3  4  5

请注意,在最新版本 0.19.1 中,这将引发一个 TypeError:

In [98]:
pd.read_csv(io.StringIO(t), header=False)

TypeError: Passing a bool to header is invalid. Use header=None for no header or header=int or list-like of ints to specify the row(s) making up the column names

关于python - 防止 pandas read_csv 将第一行视为列名的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40769691/

相关文章:

python - 在Python中连接/组合相似的列

python - 在 Excel 中导入 CSV NBA 统计数据

java - 如何验证 CSV 文件的第一行是否与标题名称匹配?

python - 为什么 Python "preemptively"在尝试计算非常大的数字时会挂起?

python - 如何在 Pandas 列中获取唯一的子串

python - 如何使用 pandas 聚合具有空值的 bool 字段?

postgresql - 防止复制 csv postgresql 上重复数据的最佳方法

python - SciPy 中的二维积分

python - 为什么 set 的 ipython 输出与 set 的 __repr__ 或 __str__ 不同?

python - 如何从文本文件中提取数字数据