Pandas:使用`sep`和`comment`参数读取CSV文件时出错

时间:2017-05-04 13:35:27

标签: python csv pandas

情况

我必须从类似CSV的文件创建一个pandas数据框,该文件具有以下特征:

  • 文件使用的分隔符可以是逗号或空格,我事先并不知道文件中的哪一个。
  • 在文件顶部可以有一个或多个注释行,以#开头。

问题

我尝试使用参数sep=Nonecomment='#'的{​​{3}}方法解决此问题。据我所知,sep=None参数告诉pandas自动检测分隔符字符,comment='#'参数告诉pandas所有以#开头的行都是应该被忽略的注释行。

单独使用时,这些参数可以正常工作。但是,当我一起使用它们时,我收到错误消息TypeError: expected string or bytes-like object。以下代码示例演示了这一点:

from io import StringIO
import pandas as pd

# Simulated data file contents
tabular_data = (
    '# Data generated on 04 May 2017\n'
    'col1,col2,col3\n'
    '5.9,7.8,3.2\n'
    '7.1,0.4,8.1\n'
    '9.4,5.4,1.9\n'
)

# This works
df1 = pd.read_csv(StringIO(tabular_data), sep=None)
print(df1)

# This also works
df2 = pd.read_csv(StringIO(tabular_data), comment='#')
print(df2)

# This will give an error
df3 = pd.read_csv(StringIO(tabular_data), sep=None, comment='#')
print(df3)

不幸的是,我真的不明白触发错误的原因。这里有人能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

试试这个:

In [186]: df = pd.read_csv(StringIO(tabular_data), sep=r'(?:,|\s+)',
                           comment='#', engine='python')

In [187]: df
Out[187]:
   col1  col2  col3
0   5.9   7.8   3.2
1   7.1   0.4   8.1
2   9.4   5.4   1.9

'(?:,|\s+)' - 用于选择逗号或任意数量的连续空格/制表符的RegEx