gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:17:10 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com