Pandas Dataframe:获取max元素的索引 [英] Pandas Dataframe: get index of max element

查看:2793
本文介绍了Pandas Dataframe:获取max元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来获取Pandas DataFrame中最大元素的索引和列。到目前为止,这是我的代码:

I am looking for a way to get both the index and the column of the maximum element in a Pandas DataFrame. Thus far, this is my code:

idx = range(0, 50, 5)
col = range(0, 50, 5)
scores = pd.DataFrame(np.zeros((len(idx), len(col))), index=idx, columns=col, dtype=float)
scores.loc[11, 16] = 5 #Assign a random element

这给了我以下DataFrame:

This gives me the following DataFrame:

  | 1   6   11  16  21  26  31  36  41  46
------------------------------------------
1 | 0   0   0   0   0   0   0   0   0   0
6 | 0   0   0   0   0   0   0   0   0   0
11| 0   0   0   5   0   0   0   0   0   0
16| 0   0   0   0   0   0   0   0   0   0
21| 0   0   0   0   0   0   0   0   0   0
26| 0   0   0   0   0   0   0   0   0   0
31| 0   0   0   0   0   0   0   0   0   0
36| 0   0   0   0   0   0   0   0   0   0
41| 0   0   0   0   0   0   0   0   0   0
46| 0   0   0   0   0   0   0   0   0   0

之后,我使用 unstack 方法:

unstacked = scores.unstack().copy()
unstacked.sort(ascending=False)

这给了我:

16  11    5
46  46    0
16  31    0
11  31    0
    36    0
...

如何获得最大值的索引和列?我希望获得包含(16,11)的数组或元组的内容。

How can I get the index and column of the maximum value? I would like to get something along the lines of an array or tuple containing (16, 11).

推荐答案

您正在寻找 idxmax

In [1332]: x
Out[1332]: 
   1  6  11  16  21  26  31  36  41  46
0  0  0   0   0   0   0   0   0   0   0
1  0  0   0   0   0   0   0   0   0   0
2  0  0   5   0   0   0   0   0   0   0
3  0  0   0   0   0   0   0   0   0   0
4  0  0   0   0   0   0   0   0   0   0
5  0  0   0   0   0   0   0   0   0   0
6  0  0   0   0   0   0   0   0   0   0
7  0  0   0   0   0   0   0   0   0   0
8  0  0   0   0   0   0   0   0   0   0
9  0  0   0   0   0   0   0   0   0   0

最大值的行:

In [1337]: max(x.idxmax())
Out[1337]: 2

最大值列(太多 max s):

Column of the max value (too many maxs):

In [1359]: x.max()[x.max() == x.max(axis=1).max()].index
Out[1359]: Index([u'11'], dtype='object')

这篇关于Pandas Dataframe:获取max元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆