在数据框的给定列中查找最大值的行索引

Find row-index of highest value in given column of dataframe

我想通过增加列 number 的值来排序 DataFrame,并获得该最大值的索引。 (这里是第二行,所以结果应该是 'BCD':

    number L-word ID
ABC 1      Lord   ABC works
BCD 25     Land   BCD works
CDE 3      Loft   CDE works

(是否有一种解决方案甚至不像我的以下 hack 那样奇怪?我通过添加另一个具有相同名称的列来解决这个问题,只是为了让我了解它通常是如何工作的)所以这是我想出的代码:

numbers_ordered = df.sort_values(['number'], ascending = False, na_position='last')
    df = numbers_ordered[:1]
    a = dict(df.head())
    b = a['ID']
    b = str(b)
    c = b[:2]

这似乎非常尴尬,应该有一个简单的选择来做到这一点,但是我在 pandas 的文档和 www.我有更改索引的想法(类似于 df = df.reset_index()),然后将旧索引转换为新列,但这仍然不是最终解决方案,因为我认为应该有一个选项"extract"我的df的top hit的索引?

尝试df['number'].argmax()

import pandas
import numpy as np
df = pandas.DataFrame(np.random.randn(10,3),columns=['Col1','Col2','Col3'])
print df
print df['Col1'].argmax()

输出

                Col1      Col2      Col3
0  0.583251 -0.014694  1.516529
1  0.274758  0.438513  0.994992
2  0.601611  1.753035  0.864451
3 -0.971775 -1.461290  0.121570
4  2.239460 -1.099298 -1.953045
5  2.314444  0.215336  0.470668
6 -0.138696  0.422923 -0.624436
7  0.602329 -0.015627  0.023715
8  0.594784  0.739058  1.094646
9 -0.104579  0.557339  1.977929

5

Pandas中查询索引的方式有很多,但不清楚你需要什么。

以下是其中的一些:

In [48]: df['number'].argmax()
Out[48]: 'BCD'

In [49]: df.index
Out[49]: Index(['ABC', 'BCD', 'CDE'], dtype='object')

In [50]: df.index == 'BCD'
Out[50]: array([False,  True, False], dtype=bool)

In [51]: df.query("index in ['BCD','ABC']")
Out[51]:
     number L-word         ID
ABC       1   Lord  ABC works
BCD      25   Land  BCD works

In [52]: df.loc[['ABC','CDE','CDE']]
Out[52]:
     number L-word         ID
ABC       1   Lord  ABC works
CDE       3   Loft  CDE works
CDE       3   Loft  CDE works