【问题标题】:How to find rows with maximum in a group in a pandas dataframe如何在熊猫数据框中的组中查找具有最大值的行
【发布时间】:2021-06-16 18:23:23
【问题描述】:

我有一个这样的熊猫数据框:

index dmc1 par dummy occur
0 d1 p1 a 1
1 d1 p2 b 1
2 d1 p3 c 1
3 d1 p3 d 2
4 d2 p1 e 1
5 d2 p2 f 1
6 d2 p2 g 2
7 d2 p3 h 1
df = pd.DataFrame({'dmc1': ['d1', 'd1', 'd1', 'd1','d2', 'd2', 'd2', 'd2'],
            'par': ['p1', 'p2', 'p3', 'p3', 'p1', 'p2', 'p2', 'p3'],
            'dummy': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
            'occur': ['1', '1', '1', '2', '1', '1', '2', '1']})

我想按“dmc1”和“par”对该表进行分组,并在每个组中找到“occur”值最高的成员并仅保留这些行。所以我希望得到这样的结果:

index dmc1 par dummy occur
0 d1 p1 a 1
0 d1 p2 b 1
0 d1 p3 d 2
0 d2 p1 e 1
0 d2 p2 g 2
0 d2 p3 h 1

我正在使用 python 3.6.10

我多次找到这个解决方案:

idx = df.groupby(['dmc1','par'])['occur'].idxmax()

df_short = data.loc[idx]

但在我的情况下,它会引发错误: AttributeError:“SeriesGroupBy”对象没有属性“idmax”

我还发现了使用“idxmax()”而不是“idmax()”的提示,但这也会引发错误: 引发ValueError

如果有一个在 python 3.6 中运行的解决方案会很高兴。

【问题讨论】:

    标签: python pandas dataframe group-by


    【解决方案1】:

    您需要先将值转换为数字:

    df['occur'] = df['occur'].astype(int)
    df_short = data.loc[df.groupby(['dmc1','par'])['occur'].idxmax()]
    

    【讨论】:

    • 天哪,是的,你是对的。有时我只见树木不见森林。
    • @Data4711 - 是的,这里的错误应该更清楚。如果我的回答有帮助,请不要忘记accept。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多