python - 熊猫分组删除重复项
问题描述
我有一个数据框(df)
a b c
1 2 20
1 2 15
2 4 30
3 2 20
3 2 15
我只想识别 c 列中的最大值
我试过了
a = df.loc[df.groupby('b')['c'].idxmax()]
但它通过删除重复分组,所以我得到
a b c
1 2 20
2 4 30
它删除了第 3 行,因为它们与第 1 行相同。
有没有办法编写代码不删除重复项?
解决方案
我认为你需要:
df = df[df['c'] == df.groupby('b')['c'].transform('max')]
print (df)
a b c
0 1 2 20
2 2 4 30
3 3 2 20
更改数据的差异:
print (df)
a b c
0 1 2 30
1 1 2 30
2 1 2 15
3 2 4 30
4 3 2 20
5 3 2 15
#only 1 max rows per groups a and b
a = df.loc[df.groupby(['a', 'b'])['c'].idxmax()]
print (a)
a b c
0 1 2 30
3 2 4 30
4 3 2 20
#all max rows per groups b
df1 = df[df['c'] == df.groupby('b')['c'].transform('max')]
print (df1)
a b c
0 1 2 30
1 1 2 30
3 2 4 30
#all max rows per groups a and b
df2 = df[df['c'] == df.groupby(['a', 'b'])['c'].transform('max')]
print (df2)
a b c
0 1 2 30
1 1 2 30
3 2 4 30
4 3 2 20