使用 pandas read_csv 方法读取 CSV 文件时,如果事先不知道行数,如何跳过这些行?
我有一个 CSV 文件,它在文件开头包含一些元数据,然后包含 header 和实际数据。
- 元数据始终以 # 符号开头,并且始终位于 CSV 文件的顶部。
- 元数据的行数不固定。
sample_file.csv 文件示例:
# Meta-Data Line 1
# Meta-Data Line 2
# Meta-Data Line 3
col1,col2,col3
a,b,c
d,e,f
g,h,i
我如何使用 Pandas read_csv 函数和 skiprows 参数来读取 csv?
df = pd.read_csv('sample_file.csv', skiprows=?)
Pandas 0.19.X 或更高版本是否支持此用例?
最佳答案
comment
是您要搜索的内容:
df = pd.read_csv('sample_file.csv', comment='#')
来自文档:
comment : str, default None
Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Like empty lines (as long as skip_blank_lines=True), fully commented lines are ignored by the parameter header but not by skiprows. For example, if comment=’#’, parsing ‘#emptyna,b,cn1,2,3’ with header=0 will result in ‘a,b,c’ being treated as the header.
关于python - Pandas 读取具有可变行的 CSV 文件以在行开头使用特殊字符跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946106/