简体   繁体   English

Pandas - 使用Groupby列出新列中的数据列

[英]Pandas - List out data columns in new columns using Groupby

I need to add new columns based on the groupby results. 我需要根据groupby结果添加新列。 Take the following dataframe for exampe. 以下面的数据框为例。

 ID      City      
 234x    Lima
 342x    Rica
 234x    Rio
 333x    NYC
 333x    SF

I have been about to use group_by to get the counts: 我一直在使用group_by获取计数:

df_GroupBy = pd.DataFrame({'count':df.groupby([ "ID"]).size()}).reset_index()

This gives an output: 这给出了一个输出:

 ID       Count
234x       2
342x       1
333x       2

What I would like to do now is get this output: 我现在想做的是得到这个输出:

 ID       City     City_2
234x       Lima     Rio
342x       Rica      
333x       NYC      SF

I have looked at both Transform and map but without much success. 我看过Transformmap但没有太大的成功。 Thanks for your help. 谢谢你的帮助。

You could 你可以

cities = df.groupby('ID')['City'].apply(lambda x: pd.Series([city for city in x])).unstack()

         0    1
ID             
234x  Lima  Rio
333x   NYC   SF
342x  Rica  NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM