给这个数据框'x':
col1 col2 col3 col4
0 5 -2 1
-5 2 -1 9
3 -7 3 5
我如何获得每列的最小值和最大值对的列表?结果将是:
list = [ [-5 , 3], [-7 , 5], [-2 , 3], [1 , 9] ]
最佳答案
您可以定义一个函数并调用 apply
传递函数名称,这将创建一个以 min 和 max 作为索引名称的 df:
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 并将值转换为列表:
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 代替:
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]]
另请注意,您可以使用
describe
和 loc
得到你想要的:In [212]:
df.describe().loc[['min','max']]
Out[212]:
col1 col2 col3 col4
min -5 -7 -2 1
max 3 5 3 9
关于python - 一个 Dataframe 的每一列的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29276301/