python - 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
解决方案
你想用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()]
推荐阅读
- java - 有什么方法可以控制 java 部分中的“style.xml”元素?
- database - 如何用sqlite计算Jaccard相似系数
- android - 使用 CameraView 在 Android 上使用 ML Kit 检测人脸
- css - 如何使用一些引导程序的移动头等舱
- ios - Swift4:如何解决“致命错误:无法使用 upperBound < lowerBound 形成范围”?(UI中的持续时间延迟)
- python - 替换 Pandas 中的逗号和点
- routes - Symfony 4.x 路由注释不适用于宅基地
- javascript - 在 for 循环之后不调用 Promise "then" 回调
- laravel - 错误:未定义的变量:视图中的数据(foreach)
- python - 在第一次请求/解析之前在蜘蛛中抓取返回项目