在pandas DataFrame中加载包含不均匀逗号的文本文件

时间:2018-06-18 16:50:31

标签: python-3.x pandas

15/09/2017, 10:20 - Jatin: Robin is the meeting on???
15/09/2017, 10:23 - Robin: No
15/09/2017, 10:23 - Robin: Thanks for the update
15/09/2017, 10:23 - Robin: can we expect it soon
15/09/2017, 10:24 - Jatin: it will be this weekend, most likely
15/09/2017, 10:24 - Jatin: kindly be prepared
15/09/2017, 10:24 - Robin: Sure no issues
15/09/2017, 10:26 - Jatin: good luck

我有一个看起来像这样的数据文件。我打算在pandas数据帧中加载它。问题是,如果我做

pd.read_csv("file.txt") 

它会抛出错误:

  

标记数据时出错。 C错误:第695行预计有2个字段,见3

有人可以建议用熊猫做最简单的方法吗?

2 个答案:

答案 0 :(得分:0)

它似乎是您尝试加载的watsapp电子邮件聊天文件。我做过类似的事情,这里有一个适合我的代码。

atempt_load=pd.read_table("WhatsApp Chat with Panda.txt")
atempt_load.columns=["namesake"] # this will load the entire message ina single column and we are just giving it a convenient name, in order to use it later
name=[]
message=[]
for i in range(len(atempt_load)):
#now there are 20 characters in front of each line before a name appears,
# we can use this and use the following coed to separate it

    name.append((atempt_load["namesake"][i])[20:25]) #since both the names are of same length this will take out the string from 20:25 words
    message.append((atempt_load["namesake"][i])[26:len(atempt_load["namesake"][i])])

如果你想要时间戳,也可以做类似的事情。

限制: 如果名称长度不同,它将无法工作,我通过在导入电子邮件中的文件之前更改聊天中的联系人姓名找到了解决方法。

我相信有人会有一个更有活力和更清洁的解决方案

答案 1 :(得分:0)

或者,更明确地指定分隔符:

pd.read_csv('test.txt', names=['timestamp', 'text'], sep=' - ') 

这将引发关于回退到python引擎的警告。这只是一个警告,可能会减少非常大的文件的性能。