Python Pandas Drop Duplicates保持倒数第二 [英] Python Pandas Drop Duplicates keep second to last

查看:218
本文介绍了Python Pandas Drop Duplicates保持倒数第二的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熊猫数据框中选择每个重复集的倒数第二种最有效的方法是什么?

What's the most efficient way to select the second to last of each duplicated set in a pandas dataframe?

例如,我基本上要执行此操作:

For instance I basically want to do this operation:

df = df.drop_duplicates(['Person','Question'],take_last=True)

但是这个:

df = df.drop_duplicates(['Person','Question'],take_second_last=True)

抽象的问题:如果重复既不是最大值也不是最小值,该如何选择要保留的重复项?

Abstracted question: how to choose which duplicate to keep if duplicate is neither the max nor the min?

推荐答案

使用groupby.apply:

With groupby.apply:

df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 2, 3, 3, 4], 
                   'B': np.arange(10), 'C': np.arange(10)})

df
Out: 
   A  B  C
0  1  0  0
1  1  1  1
2  1  2  2
3  1  3  3
4  2  4  4
5  2  5  5
6  2  6  6
7  3  7  7
8  3  8  8
9  4  9  9

(df.groupby('A', as_index=False).apply(lambda x: x if len(x)==1 else x.iloc[[-2]])
   .reset_index(level=0, drop=True))
Out: 
   A  B  C
2  1  2  2
5  2  5  5
7  3  7  7
9  4  9  9

使用不同的DataFrame,将两列作为子集:

With a different DataFrame, subset two columns:

df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 2, 3, 3, 4], 
                   'B': [1, 1, 2, 1, 2, 2, 2, 3, 3, 4], 'C': np.arange(10)})

df
Out: 
   A  B  C
0  1  1  0
1  1  1  1
2  1  2  2
3  1  1  3
4  2  2  4
5  2  2  5
6  2  2  6
7  3  3  7
8  3  3  8
9  4  4  9

(df.groupby(['A', 'B'], as_index=False).apply(lambda x: x if len(x)==1 else x.iloc[[-2]])
   .reset_index(level=0, drop=True))
Out: 
   A  B  C
1  1  1  1
2  1  2  2
5  2  2  5
7  3  3  7
9  4  4  9

这篇关于Python Pandas Drop Duplicates保持倒数第二的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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