首页 > 解决方案 > dataframe.idxmax() - 前 N 次出现

问题描述

Pandasdataframe.idxmax()函数返回请求轴上第一次出现最大值的索引。

有没有办法代替返回前 N 次出现的索引?

有问题的行:

df2 = df.loc[df.groupby(['columnA', 'columnB'], sort=False)['columnC'].idxmax()]

我希望它根据中的第 N 个最大值返回前 N 个索引df['columnC']。因此,如果df['columnC']包含值 5、10、20、50、75、90、100 和N=3,我想要值为 75、90 和 100 的行的索引。

编辑:

DataFrame 看起来像这样:

raw_data = {'cities': ['LA', 'LA', 'LA', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Boston', 'Boston', 'Boston', 'Boston', 'Boston'], 
        'location': ['pub', 'dive', 'club', 'disco', 'cinema', 'cafe', 'diner', 'bowling','supermarket', 'pizza', 'icecream', 'music'], 
        'distance': ['0', '50', '100', '5', '75', '300', '20', '40', '70', '400', '2000', '2'], 
        'score': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['cities', 'location', 'distance', 'score'])
df

标签: pythonpandas

解决方案


你想用nlargest. 这是一个例子

In [1]:
import pandas as pd
df = pd.DataFrame({'t' : [0, 8,32, 56, 96, 128],
               'T2' : [333, 500, 333, 500, 333, 460],
              })
df['t'].nlargest(3).index.tolist()

Out [1]:
[5, 4, 3]

所以这就是你要找的:

N = 3
df2 = df.loc[df.groupby(['columnA', 'columnB'], sort=False)['columnC'].nlargest(N).index.tolist()]

推荐阅读