-2

I have a DataFrame called df and it has 4 columns, like the one presented below:

A      B      C      Class
12     13     22     1
8      15     20     1
9      14     25     1
18     9      35     2 
5      14     30     2
4      12     28     2
35     87     67     3
35     82     66     3
20     7      32     4
10     8      32     4
22     7      31     4 
...    ...    ...    ...

What I want is to find the min and max for every column with respect to the class. In other words, I would like to get a result similar to the one below:

Class: 1
A: [8, 12]
B: [13, 15]
C: [20, 25]

Class: 2
A: [4, 18]
B: [9, 14]
C: [28, 35]

Class: 3
A: [35, 35]
B: [82, 87]
C: [66, 67]
...
csymvoul
  • 677
  • 3
  • 15
  • 30

2 Answers2

8

df.groupby(df['Class']).agg(['min', 'max'])

enter image description here

ilja
  • 2,592
  • 2
  • 16
  • 23
3

Another approach

df.groupby('Class').apply(lambda x: pd.Series([[min(x.A),max(x.A)],[min(x.B),max(x.B)],[min(x.C),max(x.C)]])).reset_index().rename(columns={0:'A',1:'B',2:'C'})

Output

   Class         A         B         C
0      1   [8, 12]  [13, 15]  [20, 25]
1      2   [4, 18]   [9, 14]  [28, 35]
2      3  [35, 35]  [82, 87]  [66, 67]
3      4  [10, 22]    [7, 8]  [31, 32]
iamklaus
  • 3,720
  • 2
  • 12
  • 21