gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:24:30 25 4
gpt4 key购买 nike

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

enter image description here

为了用分隔符“-”分隔两者,我试过:

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

但是 history['message'] 变成了时间而已。

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

最佳答案

我想你需要str.split使用 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: Wrong number of items passed 2, placement implies 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

关于python 数据框 - 将字符串列拆分为两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46347100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com