一个数据框的每个列的最大值和最小值 [英] Max and Min value for each colum of one 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] ]
推荐答案
您可以定义一个函数并调用apply
传递函数名,这将创建一个以min和max为索引名的df:
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
如果您坚持使用列表列表,我们可以对df进行转置并将值转换为列表:
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]]
该函数本身并不是完全必要的,因为您可以使用lambda代替:
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
这篇关于一个数据框的每个列的最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文