pandas 如何在 Dataframe 中连接行groupby列和索引中的字符串?

bt1cpqcv  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(125)

我有一个 Dataframe ,如下所示:

text
0   dog went to the store.    
0   cat is tall.
0   blue is red.
1   red is blue
1   blue is red

如何按行连接字符串,按索引连接组,使新的df看起来像这样?

text
0   dog went to the store. cat is tall. blue is red.  
1   red is blue.blue is red

我试过了,但这什么也没做,返回的行数也是一样的,不知道该怎么办:

df[['text']].groupby(df.index)['text'].transform(lambda x: ','.join(x))
7gcisfzg

7gcisfzg1#

可能的解决方案(只需将transform替换为agg):

df[['text']].groupby(df.index)['text'].agg(lambda x: ','.join(x))

输出量:

0    dog went to the store.,cat is tall.,blue is red.
1                             red is blue,blue is red
Name: text, dtype: object

相关问题