[英]How to skip an unknown number of empty lines before header on pandas.read_csv?
I want to read a dataframe from a csv file where the header is not in the first line. 我想从csv文件中读取数据帧,其中标题不在第一行。 For example:
例如:
In [1]: import pandas as pd
In [2]: import io
In [3]: temp=u"""#Comment 1
...: #Comment 2
...:
...: #The previous line is empty
...: Header1|Header2|Header3
...: 1|2|3
...: 4|5|6
...: 7|8|9"""
In [4]: df = pd.read_csv(io.StringIO(temp), sep="|", comment="#",
...: skiprows=4).dropna()
In [5]: df
Out[5]:
Header1 Header2 Header3
0 1 2 3
1 4 5 6
2 7 8 9
[3 rows x 3 columns]
The problem with the above code is that I don't now how many lines will exist before the header, therefore, I cannot use skiprows=4
as I did here. 上面代码的问题是我现在没有在标题之前存在多少行,因此,我不能像我在这里那样使用
skiprows=4
。
I aware I can iterate through the file, as in the question Read pandas dataframe from csv beginning with non-fix header . 我知道我可以遍历文件,就像从非修复头开始从csv读取pandas数据帧一样 。
What I am looking for is a simpler solution, like making pandas.read_csv
disregard any empty line and taking the first non-empty line as the header. 我正在寻找的是一个更简单的解决方案,比如让
pandas.read_csv
忽略任何空行并将第一个非空行作为标题。
您需要设置skip_blank_lines=True
df = pd.read_csv(io.StringIO(temp), sep="|", comment="#", skip_blank_lines=True).dropna()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.