gpt4 book ai didi

python - Pandas Python : append data frame - text

转载 作者:行者123 更新时间:2023-12-01 00:51:21 24 4
gpt4 key购买 nike

假设我有以下数据框。如何在同一天追加与同一用户对应的行?Python-Pandas

user date text
A 1-1 how
A 1-1 are
A 3-1 the dog
B 1-2 hi
B 1-2 there
B 3-2 be good


user date text
A 1-1 how are
A 3-1 the dog
B 1-2 hi there
B 3-2 be good

最佳答案

您正在寻找 groupby 和字符串连接:

df.groupby(['user','date'])['text'].apply(' '.join).reset_index()

Note:' '.join is a shorter version of lambda x: ' '.join(x).

完整示例:

import pandas as pd

data = '''\
user,date,text
A,1-1,how
A,1-1,are
A,3-1,the dog
B,1-2,hi
B,1-2,there
B,3-2,be good'''

fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, sep=',')

df = df.groupby(['user','date'])['text'].apply(' '.join).reset_index()
print(df)

返回:

  user date      text
0 A 1-1 how are
1 A 3-1 the dog
2 B 1-2 hi there
3 B 3-2 be good
<小时/>

如果有帮助的话,也看看这个。将列表中的所有项目分组的快速版本。

print(df.groupby(['user','date'])['text'].apply(list).reset_index())
# user date text
#0 A 1-1 [how, are]
#1 A 3-1 [the dog]
#2 B 1-2 [hi, there]
#3 B 3-2 [be good]

关于python - Pandas Python : append data frame - text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550593/

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