我有一个在列a中具有重复值的数据帧,我想删除重复项,保持列B中值最高的行。

所以这个:

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

应该变成这样:

A B
1 20
2 40
3 10

我猜可能有一种简单的方法可以做到这一点——可能就像在删除重复数据之前对DataFrame进行排序一样简单——但是我不太了解groupby的内部逻辑,无法弄清楚它。有什么建议吗?


当前回答

当已经给出的帖子回答了这个问题时,我做了一个小更改,添加了max()函数应用的列名,以提高代码的可读性。

df.groupby('A', as_index=False)['B'].max()

其他回答

这也是可行的:

a=pd.DataFrame({'A':a.groupby('A')['B'].max().index,'B':a.groupby('A')       ['B'].max().values})

最上面的答案是做了太多的工作,对于更大的数据集看起来非常慢。应用速度较慢,应尽量避免。Ix已被弃用,也应该避免使用。

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

或者简单地按所有其他列分组,然后取所需列的最大值。df。groupby (A, as_index = False) .max ()

最简单的方法是:

# First you need to sort this DF as Column A as ascending and column B as descending 
# Then you can drop the duplicate values in A column 
# Optional - you can reset the index and get the nice data frame again
# I'm going to show you all in one step. 

d = {'A': [1,1,2,3,1,2,3,1], 'B': [30, 40,50,42,38,30,25,32]}
df = pd.DataFrame(data=d)
df

    A   B
0   1   30
1   1   40
2   2   50
3   3   42
4   1   38
5   2   30
6   3   25
7   1   32


df = df.sort_values(['A','B'], ascending =[True,False]).drop_duplicates(['A']).reset_index(drop=True)

df

    A   B
0   1   40
1   2   50
2   3   42

当已经给出的帖子回答了这个问题时,我做了一个小更改,添加了max()函数应用的列名,以提高代码的可读性。

df.groupby('A', as_index=False)['B'].max()

我认为在你的情况下,你真的不需要一组。我会按B列降序排序,然后在A列删除重复项如果你愿意,你也可以有一个新的nice and 像这样干净的索引:

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index().reset_index(drop=True)