Python Pandas Drop Duplicates 倒数第二

标签 python pandas

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

例如我基本上想做这个操作:

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

但是这个:

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

抽象问题:如果副本既不是最大值也不是最小值,如何选择保留哪个副本?

最佳答案

使用 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,子集两列:

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 倒数第二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38957036/

相关文章:

python - Could not convert string to float 错误来自泰坦尼克号竞赛

Python Pandas 在 Jupyter Notebook 中以默认格式打印 Dataframe.describe()

python - Pandas DataFrame 将特定函数应用于每一列

python - 打开用于写入和读取大文件的Python

python - 我可以选择在列表中包含一个元素而不用 python 中的 else 语句吗?

python - 如何为 Django 模板中的字段提供类?

php - 在一台服务器上结合静态 HTML、Django 后端和 PHP 论坛?

python - Pandas groupby 应用 vs 具有特定功能的转换

python - 加载到 pd.DataFrame 时日期时间的奇怪行为

python - 使用 Google App Engine 将图片/视频上传到谷歌云存储