python - Pandas 读取具有可变行的 CSV 文件以在行开头使用特殊字符跳过

标签 python csv pandas

使用 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/

相关文章:

python - *.pyd 文件无法加载,但 DependancyWalker 是干净的,ProcMon 显示它已加载

python - Bcp 命令进入 Microsoft Azure

ruby - 解析文本文件并生成 CSV

python - 如何创建类别列并将其分解为新行

python - 如何获取列表并按间隔在列中添加元素?

Python 单元测试字典断言 KeyError

python - Pandas read_excel函数忽略dtype

python - 如何使用新名称(使用 for)在数据框中为每次迭代添加新列? Python

java - 使用 Jython 将参数从 Java 传递到 Python

mysql - 如何将 CSV 导入 MySQL,其中字段以逗号分隔,并且包含逗号但不包含括弧