列数据中的python pandas read_csv分隔符 [英] python pandas read_csv delimiter in column data

查看:43
本文介绍了列数据中的python pandas read_csv分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的 CSV 文件:

I'm having this type of CSV file:

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 行中用户生成的消息列中的分号而引发异常(在我看来:这很酷;或者至少不错).所有剩余的列始终具有数字 dtype.

I want to get this data into da pandas.DataFrame. But read_csv(sep=";") throws exceptions due to the semicolon in the user generated message column in line 2 (In my opinion: It's cool; or at least not bad). All remaining columns constantly have numeric dtypes.

管理这个最方便的方法是什么?

What is the most convenient method to manage this?

推荐答案

处理不带引号的定界符总是一件麻烦事.在这种情况下,由于看起来损坏的文本被三个正确编码的列包围,我们可以恢复.TBH,我只是使用标准的 Python 阅读器并从中构建一个 DataFrame:

Dealing with unquoted delimiters is always a nuisance. In this case, since it looks like the broken text is known to be surrounded by three correctly-encoded columns, we can recover. TBH, I'd just use the standard Python reader and build a DataFrame once from that:

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

然后我们可以立即保存它并得到正确引用的内容:

Then we can immediately save it and get something quoted correctly:

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

这篇关于列数据中的python pandas read_csv分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆