Peter
Peter

Reputation: 91

How to min/max value in multiple columns of a pandas dataframe?

how can i get one min/max value of several columns from a dataframe? I could not find a simple way to get these values, only with looping over the columns or converting the dataframe multiple times. I think there must be a better way to solve this.

For example, here are some code...

import pandas as pd

df = pd.DataFrame([[0,1,2,3],
                  [6,5,None,pd.NaT],
                  [8,None,9,None],
                  [None,12,7,14]], columns=list('ABCD'))

... this is what's the dataframe looks like and I want the min/max of column 'C' and 'D'.

     A     B    C     D
0  0.0   1.0  2.0     3
1  6.0   5.0  NaN   NaT
2  8.0   NaN  9.0  None
3  NaN  12.0  7.0    14

What is a good way to do this?

Additional Note: The result of both columns ['C','D'] should be one value for min (2) and one value for max (14)

Upvotes: 4

Views: 15295

Answers (3)

jezrael
jezrael

Reputation: 863701

Use DataFrame.agg with selected columns by list - ['C','D']:

df1 = df[['C','D']].agg(['min','max'])
print (df1)
       C   D
min  2.0   3
max  9.0  14

EDIT: For 2 scalars you can use:

s = df[['C','D']].stack()
print (s)
0  C     2
   D     3
2  C     9
3  C     7
   D    14
dtype: object

a = s.max()
print (a)
14

b = s.min()
print (b)
2

Upvotes: 6

Scott Boston
Scott Boston

Reputation: 153550

You can use,

df[['C','D']].min().min()
2.0

and

df[['C', 'D']].max().max()
14.0

Upvotes: 7

Mayank Porwal
Mayank Porwal

Reputation: 34086

If you are not sure about the column names, and want to do it on last 2 columns, you can do this:

In [2138]: df.iloc[:, -2:].agg(['max', 'min'])
Out[2138]: 
       C   D
max  9.0  14
min  2.0   3

Upvotes: 3

Related Questions