python - pandas 根据条件分组并添加列数据
问题描述
我已合并测试数据如下:
Device time Key score
Computers 2018-01-01 14.0 4.0
Computers 2018-01-01 11.0 4.0
Computers 2018-01-01 16.0 0.0
我需要按列 [Device,time] 和列分数的最大值对数据进行分组,并获得分配给该分数的最小键值。
我的 1 次尝试:
df_out = df_out.groupby(['Device', 'time'])['score'].max().reset_index()
输出 1:
Device time score
Computers 2018-01-01 4.0
我的 2 次尝试:
df_out = df_out.groupby(['Device', 'time'])['score', 'Key'].max().reset_index()
输出 2:
Device time score Key
Computers 2018-01-01 4.0 14.0
如何分配适当的最小密钥?
期望的输出:
Device time score Key
Computers 2018-01-01 4.0 11.0
谢谢你的辛勤工作。
解决方案
您可以使用transform
:
df[df.score.eq(df.groupby(['Device', 'time'])['score'].transform('max'))]
Device time Key score
0 Computers 2018-01-01 14.0 4.0
根据编辑:
df.groupby(['Device', 'time'],as_index=False).agg({'score':'max','Key':'min'})
Device time score Key
0 Computers 2018-01-01 4.0 11.0