繁体   English   中英

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

[英]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]

这似乎令人难以置信,应该有一个简单的选择来执行此操作,但是我在熊猫和www的文档中找不到它。 我的想法是更改索引(类似df = df.reset_index()),然后将旧索引转换为新列,但这仍然不是最终解决方案,因为我认为应该有一个选择只是“提取” “我的df热门歌曲的索引?

尝试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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM