It is a bit complicated for me to find the best approach to solve this:
I have a df:
customer id emails country
0 1 john@email.com,john12@email.com US
1 2 sara_john@email.com CA
2 3 sam@email.com,sam1900@email.com UK
3 4 sara@email.com US
4 5 NaN NaN
5 6 sam1900@email.com UK
I want to detect duplicate customer ids based on the email ids in the emails column. For example, rows (2 & 5) are considered duplicates because the same email id sam1900@email.com is shared .
I tried multiple approaches like this one:
df.join(df['emails'].apply(lambda x: pd.Series(str(x).split(','))), lsuffix="_left").drop_duplicates(subset=[0,1],keep=False).astype(str)
but the values changed between columns 0 & 1 interchangeably so the drop_duplicates did not work.
I used explode and drop_duplicates, it worked but did not yield the desired output:
df.join(df['emails'].apply(lambda x: str(x).split(',')), lsuffix="_left").explode(column='emails').drop_duplicates(subset='emails' , keep=False).groupby('customer id').agg({'emails':','.join,'country':'first'}).reset_index()
So this is the desired output:
customer id emails country
0 1 john@email.com,john12@email.com US
1 2 sara_john@email.com CA
2 4 sara@email.com US
3 5 NaN NaN
and another df for the found duplicated values to know what customer id are flagged as a duplicate:
customer id emails country duplicate_id duplicate_email
3 sam@email.com,sam1900@email.com UK 6 sam1900@email.com
Thanks for help