Max and Min value for each colum of one Dataframe
Asked Answered
B

3

5

Give this dataframe 'x':

    col1 col2 col3 col4
    0     5   -2    1 
   -5     2   -1    9
    3    -7    3    5

How I could get a list of pairs with the min and max of each column? The result would be:

list = [ [-5 , 3], [-7 , 5], [-2 , 3], [1 , 9] ]
Babbage answered 26/3, 2015 at 10:35 Comment(0)
B
20

You could define a function and call apply passing the function name, this will create a df with min and max as the index names:

In [203]:

def minMax(x):
    return pd.Series(index=['min','max'],data=[x.min(),x.max()])


df.apply(minMax)
Out[203]:
     col1  col2  col3  col4
min    -5    -7    -2     1
max     3     5     3     9

If you insist on a list of lists we can transpose the df and convert the values to a list:

In [206]:

def minMax(x):
    return pd.Series(index=['min','max'],data=[x.min(),x.max()])


df.apply(minMax).T.values.tolist()
Out[206]:
[[-5, 3], [-7, 5], [-2, 3], [1, 9]]

The function itself is not entirely necessary as you can use a lambda instead:

In [209]:

df.apply(lambda x: pd.Series([x.min(), x.max()])).T.values.tolist()
Out[209]:
[[-5, 3], [-7, 5], [-2, 3], [1, 9]]

Note also that you can use describe and loc to get what you want:

In [212]:

df.describe().loc[['min','max']]
Out[212]:
     col1  col2  col3  col4
min    -5    -7    -2     1
max     3     5     3     9
Barnum answered 26/3, 2015 at 10:39 Comment(0)
N
17

Pandas introduced the agg method for dataframes which makes this even easier:

df.agg([min, max])
Out[207]: 
     col1  col2  col3  col4
min    -5    -7    -2     1
max     3    49     6     9

That's all. Conversion into a list, if needed, can then be done as described in the accepted answer. As a bonus, this can be used with groupby also (which doesn't work well with apply):

df.groupby(by='col1').agg([min, max])
Out[208]: 
     col2     col3     col4    
      min max  min max  min max
col1                           
-5      2   2   -1  -1    9   9
 0      5  49   -2   6    1   6
 3     -7  -7    3   3    5   5
Naranjo answered 5/3, 2019 at 9:27 Comment(1)
The best way. THX U!Meiny
C
2
>>> df = pd.DataFrame([[0, 5], [-5, 2], [3, -7]])
>>> list = [ [min, max] for min, max in zip(df.min(), df.max()) ]
>>> list
[[-5, 3], [-7, 5]]

Other note: You might find DataFrame.describe method helpful: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.describe.html

Cloudy answered 26/3, 2015 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.