Search code examples
pythonpandasmaxmin

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)


Solution

  • You can use,

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

    and

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