python大 pandas :按列A删除重复项,保持列B中值最大的行 [英] python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

查看:305
本文介绍了python大 pandas :按列A删除重复项,保持列B中值最大的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以这样:

我有一个数据框,在A列中有重复值。我想删除重复项,保持列B中值最大的行。 / p>

  AB 
1 10
1 20
2 30
2 40
3 10

应该变成这样:

  AB 
1 20
2 40
3 10

Wes已经添加了一些很好的功能来删除重复项: http:// wesmckinney.com/blog/?p=340 。但是AFAICT是为了准确的重复设计,所以没有提到选择哪些行被保留的标准。



我猜想这可能是一个简单的方法, - 在删除重复项之前,可以像对数据框进行排序一样简单 - 但是我不知道groupby的内部逻辑能够很好地计算出来。任何建议?

解决方案

这需要最后一个。不是最大值:

 在[10]中:df.drop_duplicates(cols ='A',take_last = True)
出[10]:
AB
1 1 20
3 2 40
4 3 10

您还可以执行以下操作:

 在[12]中:df。 groupby('A',group_keys = False).apply(lambda x:x.ix [xBidxmax()])
输出[12]:
AB
A
1 1 20
2 2 40
3 3 10


I have a dataframe with repeat values in column A. I want to drop duplicates, keeping the row with the highest value in column B.

So this:

A B
1 10
1 20
2 30
2 40
3 10

Should turn into this:

A B
1 20
2 40
3 10

Wes has added some nice functionality to drop duplicates: http://wesmckinney.com/blog/?p=340. But AFAICT, it's designed for exact duplicates, so there's no mention of criteria for selecting which rows get kept.

I'm guessing there's probably an easy way to do this---maybe as easy as sorting the dataframe before dropping duplicates---but I don't know groupby's internal logic well enough to figure it out. Any suggestions?

解决方案

This takes the last. Not the maximum though:

In [10]: df.drop_duplicates(cols='A', take_last=True)
Out[10]: 
   A   B
1  1  20
3  2  40
4  3  10

You can do also something like:

In [12]: df.groupby('A', group_keys=False).apply(lambda x: x.ix[x.B.idxmax()])
Out[12]: 
   A   B
A       
1  1  20
2  2  40
3  3  10

这篇关于python大 pandas :按列A删除重复项,保持列B中值最大的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆