从数据框中删除反向重复项 [英] Remove reverse duplicates from dataframe
本文介绍了从数据框中删除反向重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两列的数据框,分别是 A
和 B
。在这种情况下, A
和 B
的顺序并不重要。例如,我会认为(0,50)
和(50,0)
是重复的。在熊猫中,从数据框中删除这些重复项的有效方法是什么?
I have a data frame with two columns, A
and B
. The order of A
and B
is unimportant in this context; for example, I would consider (0,50)
and (50,0)
to be duplicates. In pandas, what is an efficient way to remove these duplicates from a dataframe?
import pandas as pd
# Initial data frame.
data = pd.DataFrame({'A': [0, 10, 11, 21, 22, 35, 5, 50],
'B': [50, 22, 35, 5, 10, 11, 21, 0]})
data
A B
0 0 50
1 10 22
2 11 35
3 21 5
4 22 10
5 35 11
6 5 21
7 50 0
# Desired output with "duplicates" removed.
data2 = pd.DataFrame({'A': [0, 5, 10, 11],
'B': [50, 21, 22, 35]})
data2
A B
0 0 50
1 5 21
2 10 22
3 11 35
理想情况下,输出将按列 A
的值排序。
Ideally, the output would be sorted by values of column A
.
推荐答案
您可以在删除重复项之前对数据框的每一行进行排序:
You can sort each row of the data frame before dropping the duplicates:
data.apply(lambda r: sorted(r), axis = 1).drop_duplicates()
# A B
#0 0 50
#1 10 22
#2 11 35
#3 5 21
如果您希望对结果进行排序列 A
:
If you prefer the result to be sorted by column A
:
data.apply(lambda r: sorted(r), axis = 1).drop_duplicates().sort_values('A')
# A B
#0 0 50
#3 5 21
#1 10 22
#2 11 35
这篇关于从数据框中删除反向重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文