python数据框 - 将字符串列拆分为两列

时间:2017-09-21 14:51:59

标签: python pandas split

我正在玩Whatsapp的历史聊天。 我想将消息列拆分为两列 - 时间和消息。

enter image description here

为了用分隔符“ - ”拆分两个,我尝试了:

history['message'] = pd.DataFrame([line.split(" - ",1) for line in history['message']])

但历史['消息']成为唯一的时间。

我不明白为什么,因为line.split(“ - ”,1)假设最多给出2个元素的列表。

1 个答案:

答案 0 :(得分:4)

我认为您需要str.splitexpand=True一起返回DataFrame

history = pd.DataFrame({'message':['a - b','c - d - r']})

history[['a','b']] = history['message'].str.split(' - ', n=1, expand=True)
print (history)
     message  a      b
0      a - b  a      b
1  c - d - r  c  d - r

如果没有NaNs使用:

history[['a','b']] = pd.DataFrame([line.split(" - ", 1) for line in history['message']])

对我来说,返回错误:

history['a'] = pd.DataFrame([line.split(" - ", 1) for line in history['message']])
print (history)
  

ValueError:传递的项目数量错误2,展示位置意味着1

因此,如果您正常工作,请尝试检查分隔符,因为它似乎没有split

样品:

history['a'] = history['message'].str.split('^', n=1, expand=True)
print (history)
     message          a
0      a - b      a - b
1  c - d - r  c - d - r
相关问题