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

How to aggregate only one column pandas python 2.7

I try to aggregate based on one column "col1" like this and keep same value from other columns:

df_input 

       col1      col2    col3    col4  
0       ID1      DE      69      min-8     
1       ID1      DZ      69      min-8
2       ID3      DA      54      min-15
3       ID3      AC      54      min-15
4       ID3      RC      54      min-15
5       ID8      UC      2       min-40
6       ID8      TC      2       min-40
7       ID8      VC      2       min-40
8       ID8      WC      2       min-40
9       ID7      XC      4       min-7



df_output 

           col1      col2             col3    col4  
    0       ID1      DE,DZ            69      min-8     
    1       ID3      DA,AC,RC         54      min-15
    2       ID8      UC,TC,VC,WC      2       min-40
    3       ID7      XC               4       min-7
question from:https://stackoverflow.com/questions/65641270/how-to-aggregate-only-one-column-pandas-python-2-7

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

1 Reply

0 votes
by (71.8m points)

Let's try breaking the below code.

  • First, group your dataframe by col1, and then perform .agg on the grouped object.
  • We will then use a lambda function on col2 to get all of it's elements in a list
  • Let's use the argument 'first', to show that we want to keep only the first element of col3 and col4
  • Then, reset the index.
agg_df = (df.groupby('col1')
      .agg({'col2': lambda x: x.tolist(),'col3':'first','col4':'first'})
      .reset_index())     

print(agg_df)

  col1              col2  col3    col4
0  ID1          [DE, DZ]    69   min-8
1  ID3      [DA, AC, RC]    54  min-15
2  ID7              [XC]     4   min-7
3  ID8  [UC, TC, VC, WC]     2  min-40

To then convert col2 from having it's values stored in a list to proper string, we can join it's elements using a ,:

agg_df['col2'].apply(lambda x: ','.join(str(i) for i in x))

Out[16]: 
0          DE,DZ
1       DA,AC,RC
2             XC
3    UC,TC,VC,WC
Name: col2, dtype: object  

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

...