Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

Python,Pandas,DataFrame, add new column doing SQL GROUP_CONCAT equivalent

My question is very similar to the one asked but unanswered here Replicating GROUP_CONCAT for pandas.DataFrame

I have a Pandas DataFame which I want to group concat into a data frame

+------+---------+  
| team | user    |  
+------+---------+  
| A    | elmer   |  
| A    | daffy   |  
| A    | bugs    |  
| B    | dawg    |  
| A    | foghorn |  
+------+---------+  

Becoming

+------+---------------------------------------+  
| team | group_concat(user)                    |  
+------+---------------------------------------+  
| A    | elmer,daffy,bugs,foghorn              |  
| B    | dawg                                  | 
+------+---------------------------------------+  

As answeed in the original topic, it can be done via any of these:

df.groupby('team').apply(lambda x: ','.join(x.user))
df.groupby('team').apply(lambda x: list(x.user))
df.groupby('team').agg({'user' : lambda x: ', '.join(x)})

But the resulting object is not a Pandas Dataframe anymore. How can I get the GROUP_CONCAT results in the original Pandas DataFrame as a new column?

Cheers

question from:https://stackoverflow.com/questions/65641808/python-pandas-dataframe-add-new-column-doing-sql-group-concat-equivalent

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can apply list and join after grouping by, then reset_index to get the dataframe.

output_df = df.groupby('team')['user'].apply(lambda x: ",".join(list(x))).reset_index()
output_df.rename(columns={'user': 'group_concat(user)'})

    team    group_concat(user)
0   A   elmer,daffy,bugs,foghorn
1   B   dawg

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...