【发布时间】:2017-05-01 17:17:20
【问题描述】:
已经看过here 和here,它们接近我认为我看到的核心问题,但在其他方面得到了解决。
我正在尝试解析一个 CSV,它有一个字段,现在需要在其中包含一个逗号,要求我们将该字段用引号引起来。它是引号中的唯一字段。
我们的分隔符 (sep) 是逗号,我们现在添加引号 (quotechar) 的字符串分隔符。
我把它归结为这个。在我看来, sep 和 quotechar 应用程序的顺序是关键问题,导致使用 quotechar 的行中带有 sep 的行将永远无法工作。
最后一行注释掉的数据文件。
$ cat simple.csv
column1,column2, column3
one, two, three
one, two, "three"
#one, "two, two_again", three
$
代码:
df = pd.read_csv( simple_file, sep=',', header=0, comment='#', quotechar='"')
print df
输出:
column1 column2 column3
0 one two three
1 one two "three"
现在,在引用的字符串中添加具有 sep 字符的最后一行。
数据文件:
$ cat simple.csv
column1,column2, column3
one, two, three
one, two, "three"
one, "two, two_again", three
$
输出失败:
pandas/parser.pyx in pandas.parser.raise_parser_error (pandas/parser.c:22649)()
CParserError: Error tokenizing data. C error: Expected 3 fields in line 4, saw 4
我相信我想强制 Pandas 首先在每一行上使用引号分隔符,然后使用分隔符,因为它正在做相反的事情。似乎无法弄清楚如何。有没有办法告诉熊猫这是我找不到的?
【问题讨论】:
-
去掉空格或将空格定义为分隔符的一部分。然后只需指定 header=None 即可读取文件,其余部分由默认值处理。
标签: python string csv parsing pandas