大熊猫dataframe.idxmax()函数在请求轴上返回第一次最大值的索引。
是否有方法返回前N个出现次数的索引?
有问题的一行:

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

我希望它返回前N个索引数,这些索引数基于df['columnC']中的第N个最大值。因此,如果df['columnC']包含值5、10、20、50、75、90、100和N=3,则需要值为75、90和100的行的索引。
编辑:
数据帧如下所示:
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

要在迭代“距离”窗口(100个单位)内返回“位置”和最高“分数”:
df['distance'] = pd.to_numeric(df['distance'])
df['bin100'] = pd.cut(df['distance'], np.arange(0, 2001, 100), include_lowest=True, labels=False)
df = df.loc[df.groupby(['cities', 'bin100'], sort=False)['score'].idxmax()]

最佳答案

具有特定的自定义功能:

In [197]: df = pd.DataFrame({'col': [1,2,3,5,2,1,0,5,4,5,1,3,5,1,5]})

In [198]: def top_max_idx(df, col, n):
     ...:     return df[col][df[col] == df[col].max()].index[:n].tolist()
     ...:

In [199]: top_max_idx(df, 'col', 3)
Out[199]: [3, 7, 9]

关于python - dataframe.idxmax()-前N次出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57664620/

10-12 06:39