Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 349
Peter Avatar asked Oct 22 '25 16:10

Peter


2 Answers

You can use,

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

and

df[['C', 'D']].max().max()
14.0
like image 74
Scott Boston Avatar answered Oct 25 '25 04:10

Scott Boston


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
like image 43
jezrael Avatar answered Oct 25 '25 05:10

jezrael