列数据中的python pandas read_csv分隔符

时间:2015-06-17 17:58:21

标签: python csv python-3.x pandas delimiter

我有这种类型的CSV文件:

12012;My Name is Mike. What is your's?;3;0 
1522;In my opinion: It's cool; or at least not bad;4;0
21427;Hello. I like this feature!;5;1

我想将此数据输入da pandas.DataFrame。 但是read_csv(sep=";")因第2行中用户生成的消息列中的分号而引发异常(在我看来:它很酷;或者至少不坏)。所有剩余的列始终具有数字dtypes。

管理此方法最方便的方法是什么?

1 个答案:

答案 0 :(得分:7)

处理不带引号的分隔符总是令人讨厌的。在这种情况下,由于看起来已知破碎的文本被三个正确编码的列包围,我们可以恢复。 TBH,我只是使用标准的Python阅读器并从中构建一次DataFrame:

import csv
import pandas as pd

with open("semi.dat", "r", newline="") as fp:
    reader = csv.reader(fp, delimiter=";")
    rows = [x[:1] + [';'.join(x[1:-2])] + x[-2:] for x in reader] 
    df = pd.DataFrame(rows)

产生

       0                                              1  2  3
0  12012               My Name is Mike. What is your's?  3  0
1   1522  In my opinion: It's cool; or at least not bad  4  0
2  21427                    Hello. I like this feature!  5  1

然后我们可以立即保存并正确引用:

In [67]: df.to_csv("fixedsemi.dat", sep=";", header=None, index=False)

In [68]: more fixedsemi.dat
12012;My Name is Mike. What is your's?;3;0
1522;"In my opinion: It's cool; or at least not bad";4;0
21427;Hello. I like this feature!;5;1

In [69]: df2 = pd.read_csv("fixedsemi.dat", sep=";", header=None)

In [70]: df2
Out[70]: 
       0                                              1  2  3
0  12012               My Name is Mike. What is your's?  3  0
1   1522  In my opinion: It's cool; or at least not bad  4  0
2  21427                    Hello. I like this feature!  5  1