如何将带有一些引号行的 csv 导入 pandas?

问题描述 投票:0回答:2

我有一个结构如下的 csv:

project, location, badness
foo, N/A, 0
bar, 'path/to/file:[7,23]', 120

我想将其导入 Pandas 数据框。当我现在使用

pd.read_csv(filename, quote="'", sep=".\s+")
时,我会得到如下列:

project   location           badness
foo       N/A                0
bar       'path/to/file:[7   23]'       120

最后一个悬空列未命名。

如何以尊重引号的方式导入它?也就是说,如何让“位置”列在第二行有

'path/to/file:[7,23]'

python pandas csv parsing
2个回答
0
投票

尝试将分隔符更改为

",\s+"
:

from io import StringIO

import pandas as pd

text = """\
project, location, badness
foo, N/A, 0
bar, 'path/to/file:[7,23]', 120"""

df = pd.read_csv(StringIO(text), quotechar="'", sep=r",\s+", engine="python")
print(df)

打印:

  project               location  badness
0     foo                    NaN        0
1     bar  'path/to/file:[7,23]'      120

0
投票

使用

quotechar="'"
指定字段可以用单引号引起来,并使用
skipinitialspace
跳过逗号后面的空格。

pd.read_csv(filename, quotechar="'", skipinitialspace=True)

无需指定分隔符。

© www.soinside.com 2019 - 2024. All rights reserved.