开发者

How to concat strings in rows groupby column and index in dataframe?

开发者 https://www.devze.com 2022-12-07 22:34 出处:网络
I have a dataframe that looks like this: text 0dog went to the store. 0cat is tall. 0blue is red. 1red is blue

I have a dataframe that looks like this:

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

How do I concat the strings by row and group by index, so that the new df looks like this?:

    text
0   dog went to the 开发者_开发问答store. cat is tall. blue is red.  
1   red is blue.blue is red

I've tried, but this is doing nothing and returns back the same number of rows, not sure where to go from here:

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


A possible solution (just replace transform by agg):

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

Output:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号