find duplicate rows in a pandas dataframe(在 pandas 数据框中查找重复行)
问题描述
我正在尝试在 pandas 数据框中查找重复行.
I am trying to find duplicates rows in a pandas dataframe.
df=pd.DataFrame(data=[[1,2],[3,4],[1,2],[1,4],[1,2]],columns=['col1','col2'])
df
Out[15]:
col1 col2
0 1 2
1 3 4
2 1 2
3 1 4
4 1 2
duplicate_bool = df.duplicated(subset=['col1','col2'], keep='first')
duplicate = df.loc[duplicate_bool == True]
duplicate
Out[16]:
col1 col2
2 1 2
4 1 2
有没有办法添加引用第一个副本(保留的那个)的索引的列
Is there a way to add a column referring to the index of the first duplicate (the one kept)
duplicate
Out[16]:
col1 col2 index_original
2 1 2 0
4 1 2 0
注意:在我的情况下,df 可能非常大....
Note: df could be very very big in my case....
推荐答案
使用groupby
,新建一列索引,然后调用duplicated
:
Use groupby
, create a new column of indexes, and then call duplicated
:
df['index_original'] = df.groupby(['col1', 'col2']).col1.transform('idxmin')
df[df.duplicated(subset=['col1','col2'], keep='first')]
col1 col2 index_original
2 1 2 0
4 1 2 0
<小时>
详情
我groupby
前两列然后调用transform
+ idxmin
得到每个组的第一个索引.
I groupby
first two columns and then call transform
+ idxmin
to get the first index of each group.
df.groupby(['col1', 'col2']).col1.transform('idxmin')
0 0
1 1
2 0
3 3
4 0
Name: col1, dtype: int64
duplicated
给了我想要保留的值的布尔掩码:
duplicated
gives me a boolean mask of values I want to keep:
df.duplicated(subset=['col1','col2'], keep='first')
0 False
1 False
2 True
3 False
4 True
dtype: bool
剩下的只是布尔索引.
这篇关于在 pandas 数据框中查找重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 pandas 数据框中查找重复行


- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01