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
1.0k views
in Technique[技术] by (71.8m points)

python - Comma separated values from pandas GroupBy

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

example:

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

the out put should be like:

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

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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


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

...