使用DataFrame的groupby方法,并将所有行连接成一行。

huangapple go评论58阅读模式
英文:

Use groupby on dataframe and concenate all rows into one

问题

I have this dataframe:

ID x y z
1 纽约 加利福尼亚
2 佛蒙特;纽约 南卡罗来纳 佛罗里达
2 俄勒冈 德克萨斯 佛罗里达;科罗拉多
3 新泽西
1 夏威夷 犹他

I'm trying to group by ID, and merge column x, y, and z into one column.

Output should be:

ID 地理位置
1 纽约; 加利福尼亚; 夏威夷; 犹他
2 佛蒙特; 纽约; 南卡罗来纳; 俄勒冈; 德克萨斯; 佛罗里达; 科罗拉多; 佛罗里达
3 新泽西

I tried with the following piece of code:

save = df.groupby('ID')['x', 'y', 'z'].apply(lambda x: ';'.join(set(x.dropna()))).reset_index()
英文:

I have this dataframe :

ID x y z
1 new york california
2 vermont; new york carolina n florida
2 oregon texas florida; colorado
3 new jersey
1 hawai utah

I'm trying to group by ID, and merge column x, y, and z into one column.

Output should be :

ID geo
1 new york; california; hawai; utah
2 vermont; new york; carolina n; oregon; texas; florida; colorado; florida
3 new jersey

I tried with the following piece of code :

save = df.groupby('ID').agg(lambda x: ';'.join(set(x)))

But it doesn't work.

答案1

得分: 1

尝试在连接之前堆叠数据:

(df.groupby('ID', group_keys=False)
   .apply(lambda x: '; '.join(x.stack().dropna()))
   .reset_index(name='geo')
)

输出:

   ID                                                geo
0   1               new york; california; hawai; utah
1   2  vermont; new york; carolina n; florida; oregon
2   3                                        new jersey
英文:

Try stack the data before join:

(df.groupby('ID',group_keys=False)
   .apply(lambda x: '; '.join(x.stack().dropna()) )
   .reset_index(name='geo')
)

Output:

   ID                                                geo
0   1               new york; california; hawai; utah 
1   2  vermont; new york; carolina n; florida; oreg...
2   3                                        new jersey 

huangapple
  • 本文由 发表于 2023年8月5日 01:33:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定