逗号分隔的值与pandas GroupBy [英] Comma separated values from pandas GroupBy

查看:108
本文介绍了逗号分隔的值与pandas GroupBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在连接值时是否可以删除数据框中的重复项

i trying to find out if there is away to remove duplicate in my data frame while concatenating the value

示例:

df
   key  v1  v2
0  1   n/a  a
1  2   n/a  b
2  3   n/a  c
3  2   n/a  d
4  3   n/a  e

输出应该是这样的:

 df_out
   key v1   v2
0  1   n/a  a
1  2   n/a  b,d
2  3   n/a  c,e

我尝试使用df.drop_duplicates()和一些循环来保存v2列值,但目前还没有. 我正在尝试通过使用Pandas使其美观而干净,并且没有循环.

I try using df.drop_duplicates() and some loop to save the v2 column value and nothing yet. i'm trying to do it nice and clean with out loop by using Pandas.

有人知道熊猫可以做到这一点吗?

some one know a way pandas can do it?

推荐答案

假设您有两列,这应该很容易.使用groupby + agg. v1应该由first聚合,而v2应该由','.join聚合.

This should be easy, assuming you have two columns. Use groupby + agg. v1 should be aggregated by first, and v2 should be aggregated by ','.join.

df
   key  v1 v2
0    1 NaN  a
1    2 NaN  b
2    3 NaN  c
3    2 NaN  d
4    3 NaN  e

(df.groupby('key')
   .agg({'v1' : 'first', 'v2' : ','.join})
   .reset_index()
   .reindex(columns=df.columns))

   key  v1   v2
0    1 NaN    a
1    2 NaN  b,d
2    3 NaN  c,e

如果有多个此类列需要相同的聚合,则构建一个名为f的聚合字典并将其传递给agg.

If you have multiple such columns requiring the same aggregation, build an agg dict called f and pass it to agg.

这篇关于逗号分隔的值与pandas GroupBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆