gpt4 book ai didi

python - Pandas :在数据框中找到每个系列的最大值

转载 作者:行者123 更新时间:2023-11-28 21:47:09 29 4
gpt4 key购买 nike

考虑这个数据:

df = pd.DataFrame(np.random.randint(0,20,size=(5, 4)),
columns=list('ABCD'),
index=pd.date_range('2016-04-01', '2016-04-05'))

date A B C D
1/1/2016 15 5 19 2
2/1/2016 18 1 14 11
3/1/2016 10 16 8 8
4/1/2016 7 17 17 18
5/1/2016 10 15 18 18

哪里date是索引

我想取回的是(date, <max>, <series_name>)的元组对于每一列:

   2/1/2016, 18, 'A'
4/1/2016, 17, 'B'
1/1/2016, 19, 'C'
4/1/2016, 18, 'D'

这如何在惯用的 pandas 中完成?

最佳答案

你可以使用 idxmaxmax为此设置 axis=0 然后加入它们:

np.random.seed(632)

df = pd.DataFrame(np.random.randint(0,20,size=(5, 4)), columns=list('ABCD'))

In [28]: df
Out[28]:
A B C D
0 10 14 16 1
1 12 13 8 8
2 8 16 11 1
3 8 1 17 12
4 4 2 1 7

In [29]: df.idxmax(axis=0)
Out[29]:
A 1
B 2
C 3
D 3
dtype: int64

In [30]: df.max(axis=0)
Out[30]:
A 12
B 16
C 17
D 12
dtype: int32


In [32]: pd.concat([df.idxmax(axis=0) , df.max(axis=0)], axis=1)
Out[32]:
0 1
A 1 12
B 2 16
C 3 17
D 3 12

关于python - Pandas :在数据框中找到每个系列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36931250/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com