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

所以这个:

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

应该变成这样:

A B
1 20
2 40
3 10

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


当前回答

最简单的方法是:

# 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

其他回答

你也可以试试这个

df.drop_duplicates(subset='A', keep='last')

我参考了https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html

我将首先对数据帧进行排序,列B降序,然后删除列A的重复项并保持优先

df = df.sort_values(by='B', ascending=False)
df = df.drop_duplicates(subset='A', keep="first")

没有任何分组

最简单的方法是:

# 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

与所选答案非常相似的方法,但是按多列对数据帧进行排序可能是一种更简单的编码方法。

首先,根据“A”和“B”列对日期帧进行排序,ascending=False确保它从最高值到最低值进行排序:

df.sort_values(["A", "B"], ascending=False, inplace=True)

然后,删除重复项,只保留第一项,它已经是值最高的项:

df.drop_duplicates(inplace=True)

这也是可行的:

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