Home > OS >  How to group same values/labels and select specific values from other columns?
How to group same values/labels and select specific values from other columns?

Time:05-31

I have a dataframe like this one below with depth values (top and bot) for specific classes:

df = pd.DataFrame({"class":["a","a","b","b","b","c","c","c","c","c","c"],
                   "top":[5.1,6.9,12.1,14.2,16,2.1,2.9,3.8,4.5,5,6.1],
                   "bot":[5.8,7.1,13.8,15.9,16.7,2.8,3.5,4.1,4.9,5.5,7]})

   class   top   bot
0      a   5.1   5.8
1      a   6.9   7.1
2      b  12.1  13.8
3      b  14.2  15.9
4      b  16.0  16.7
5      c   2.1   2.8
6      c   2.9   3.5
7      c   3.8   4.1
8      c   4.5   4.9
9      c   5.0   5.5
10     c   6.1   7.0

I would like to group/concatenate these classes into one row for each class and the minimum value as top and the max value as bot, like this:

  class   top   bot
0     a   5.1   7.1
1     b  12.1  16.7
2     c   2.1   7.0

Anyone could help me?

CodePudding user response:

Let us do groupby with agg

out = df.groupby('class',as_index=False).agg({'top':'first','bot':'last'})
Out[352]: 
  class   top   bot
0     a   5.1   7.1
1     b  12.1  16.7
2     c   2.1   7.0
  • Related