我必须从类似CSV的文件创建一个pandas数据框,该文件具有以下特征:
#
开头。我尝试使用参数sep=None
和comment='#'
的{{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)
不幸的是,我真的不明白触发错误的原因。这里有人能帮我解决这个问题吗?
答案 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