使用header/skiprows参数读取csv后,参数值变为NaN

2024-04-27 02:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试打开一个csv文件,文件头跨越多行。为了避免处理多索引,我使用header参数跳过一些行,但是所有值都变成了nan。在

重现错误的示例:

,,
x,a,c
y,b,d
labels,l1,l2
2016-01-01,1,6
2016-01-02,2.0,7.0
2016-01-03,3.0,8

在测试.csv在

^{pr2}$

或者

t = pandas.read_csv('test.csv', header=[3], index_col=[0] )

产生相同的输出

labels       l1   l2
2016-01-01  NaN  NaN
2016-01-02  NaN  NaN
2016-01-03  NaN  NaN

[3 rows x 2 columns]

当我使用所有3个标题行时

t = pandas.read_csv('test.csv', header=[1,2,3], index_col=[0] )

它起作用了,我可以访问数据。在

是我漏掉了什么还是这是个虫子?在

ps:我现在使用MultiIndex,我遇到了一个问题,因为我忘记了一个参数(头有8行…)


Tags: 文件csvtestl1pandasread参数index
2条回答

这个怎么样:

my_file = 'test.csv'
df = pd.read_csv(my_file, sep=',', names=['labels', 'l1', 'l2'], skiprows=4, header=None)

完全忘掉前4行,自己指定标题。在

试试这个:

In [20]: pd.read_csv(filename, skiprows=3)
Out[20]:
       labels   l1   l2
0  2016-01-01  1.0  6.0
1  2016-01-02  2.0  7.0
2  2016-01-03  3.0  8.0

相关问题 更多 >