Give this dataframe ‘x’:
JavaScript
x
5
1
col1 col2 col3 col4
2
0 5 -2 1
3
-5 2 -1 9
4
3 -7 3 5
5
How I could get a list of pairs with the min and max of each column? The result would be:
JavaScript
1
2
1
list = [ [-5 , 3], [-7 , 5], [-2 , 3], [1 , 9] ]
2
Advertisement
Answer
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:
JavaScript
1
12
12
1
In [203]:
2
3
def minMax(x):
4
return pd.Series(index=['min','max'],data=[x.min(),x.max()])
5
6
7
df.apply(minMax)
8
Out[203]:
9
col1 col2 col3 col4
10
min -5 -7 -2 1
11
max 3 5 3 9
12
If you insist on a list of lists we can transpose the df and convert the values to a list:
JavaScript
1
10
10
1
In [206]:
2
3
def minMax(x):
4
return pd.Series(index=['min','max'],data=[x.min(),x.max()])
5
6
7
df.apply(minMax).T.values.tolist()
8
Out[206]:
9
[[-5, 3], [-7, 5], [-2, 3], [1, 9]]
10
The function itself is not entirely necessary as you can use a lambda instead:
JavaScript
1
6
1
In [209]:
2
3
df.apply(lambda x: pd.Series([x.min(), x.max()])).T.values.tolist()
4
Out[209]:
5
[[-5, 3], [-7, 5], [-2, 3], [1, 9]]
6
Note also that you can use describe
and loc
to get what you want:
JavaScript
1
8
1
In [212]:
2
3
df.describe().loc[['min','max']]
4
Out[212]:
5
col1 col2 col3 col4
6
min -5 -7 -2 1
7
max 3 5 3 9
8