python去掉最高分_Python-根据列的最大值删除重复项

I am not really good with pandas, and I think pandas should solve my problem:

I have a text file, that contains data (id1;id2;value1;value2;value3)

1;2;30;40;20.3;

1;2;30;42;26.2;

3;5;12;55;10.7;

3;5;12;23;8.7;

3;5;12;33;11.2;

24;12;1;553;1.1;

24;12;1;23;1.9;

As a result, I want to keep lines, that have equal id1, id2, value1, and higher value3. Value2 is not important, but it needs to be kept, e.g.

1;2;30;42;26.2;

3;5;12;33;11.2;

24;12;1;23;1.9;

解决方案

You need DataFrameGroupBy.idxmax for indexes of max value of value3 and thes select DataFrame by loc:

print (df.groupby(['id1','id2','value1']).value3.idxmax())

id1 id2 value1

1 2 30 1

3 5 12 4

24 12 1 6

Name: value3, dtype: int64

df = df.loc[df.groupby(['id1','id2','value1']).value3.idxmax()]

print (df)

id1 id2 value1 value2 value3 a

1 1 2 30 42 26.2 NaN

4 3 5 12 33 11.2 NaN

6 24 12 1 23 1.9 NaN

Another possible solution is sort_values by column value3 and then groupby with GroupBy.first:

df = df.sort_values('value3', ascending=False)

.groupby(['id1','id2','value1'], sort=False)

.first()

.reset_index()

print (df)

id1 id2 value1 value2 value3 a

0 1 2 30 42 26.2 NaN

1 3 5 12 33 11.2 NaN

2 24 12 1 23 1.9 NaN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值