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
Note: df could be very very big in my case....
Finding duplicate rows To take a look at the duplication in the DataFrame as a whole, just call the duplicated() method on the DataFrame. It outputs True if an entire row is identical to a previous row.
You can set 'keep=False' in the drop_duplicates() function to remove all the duplicate rows. For E.x, df. drop_duplicates(keep=False) .
To find & select the duplicate all rows based on all columns call the Daraframe. duplicate() without any subset argument. It will return a Boolean series with True at the place of each duplicated rows except their first occurrence (default value of keep argument is 'first').
Code 1: Find duplicate columns in a DataFrame. To find duplicate columns we need to iterate through all columns of a DataFrame and for each and every column it will search if any other column exists in DataFrame with the same contents already. If yes then that column name will be stored in the duplicate column set.
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
Details
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
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
The rest is just boolean indexing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With