Q: Drop duplicates with some complex logic I have a data frame with two values, car_id and owner_type.
Based on the duplicates on car_id, I want to treat the values in a different way (based on the values) in that duplicated subset of owner_type.
If a car_id is duplicated, and taking into consideration that owner_type can only be 'owner' or 'lender':

*

*If the duplicated pair is both owner, fill the owner_type with missing value.

*If the duplicated pair is owner and lender (no matter which order), keep the owner.

*If the duplicated pair is both lender, fill the value owner_type with missing value.

The following initial data set:




`'

car_id
owner_type




0
1
owner



1
1
owner



2
2
owner



3
2
lender



4
3
lender



5
3
owner



6
4
lender



7
4
lender
'




Should result into:




 '

car_id
owner_type




0
1
N/A



1
1
N/A



2
2
owner



3
2
N/A



4
3
N/A



5
3
owner



6
4
N/A



7
4
N/A
'




A: Try this:
def get_owner(frame):
    # only owner or only lender
    if frame.nunique() == 1:
        return pd.Series([np.nan] * 2)
    return frame.replace('lender', np.nan)

# apply to each group of car_id and store in df
df['owner_type'] = df.groupby('car_id').owner_type.apply(get_owner).values

Result:
   car_id owner_type
0       1        NaN
1       1        NaN
2       2      owner
3       2        NaN
4       3        NaN
5       3      owner
6       4        NaN
7       4        NaN

