2017-02-25 116 views
0

我在python中使用熊猫时遇到问题。熊猫不会跳过带有index_col函数的空行

我需要使用国家/地区列索引我的数据帧。但列一行之后的空行该CSV文件看起来像这样:

0 Televison, Physicians, and Life Expectancy 
1 NaN, NaN, NaN, NaN, NaN, NaN 
2 country, life expectancy, people/TV, people/physician, female life expectancy, male life expectancy 
3 NaN, NaN, NaN, NaN, NaN, NaN (I need to skip this line) 
4 value, value, value, value, value, value, 
5 value, value, value, value, value, value, 
... 
... 

我试图跳过这样的标题和第一实际数据线之间的空行:

tvdf = pd.read_csv(infile, sep=',', header=2, skiprows=[3], nrows=40, index_col='Country', skip_blank_lines=True) 

作为回报,它成功地把国家列作为索引。但是,在index_col函数内,skiplines和skip_blank_lines都不起作用。我的解释是:如果我使用country列作为索引,它会将空行(NaN)识别为第一个索引名称。并且skip_range和skip_blank_lines都不会在index_col函数中生效。我在没有index_col的情况下尝试了它,它会自动忽略没有任何skiprows或skip_blank_lines语句的非值行。

我一直在网上搜索这个问题,并没有发现任何相关的问题。 所以在这个阶段,也许我可以操纵cvs文件并手动删除空行或者是否有任何人有处理这个问题的经验?

我感谢您的帮助!

回答

0

使用skiprows=[0, 1, 3]

pd.read_clipboard(
    sep=',', skipinitialspace=True, skiprows=[0, 1, 3] 
) 

enter image description here