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

python数据帧-将字符串列拆分为两列,python,pandas,split,Python,Pandas,Split,我在玩Whatsapp的历史聊天。 我想将消息列拆分为两列—时间和消息 为了用分隔符“-”将两者分开,我尝试: history['message'] = pd.DataFrame([line.split(" - ",1) for line in history['message']]) 但是历史[信息]变成了时间 我不明白为什么,因为.split(“-”,1)行假设最多给出2个元素的列表。我认为您需要使用expand=True返回DataFrame: history = pd.DataFra

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

为了用分隔符“-”将两者分开,我尝试:

history['message'] = pd.DataFrame([line.split(" - ",1) for line in history['message']])
但是历史[信息]变成了时间

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

我认为您需要使用
expand=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

因此,如果您认为它有效,请尝试检查分隔符,因为它似乎没有拆分

样本:

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