How to remove uncommon unique values from labels in 2 pandas dataframes

I have 2 pandas dataframes. df1 and df2. the label column is the last column.

df1.label.unique()

output:

array([1,  2,  9, 7])

df2.label.unique()

output:

array([1,  2,  8, 11])

How can I delete rows in both dataframes that have uncommon unique values in label column so the two dataframes both have only 1 and 2 label values?

1 answer

  • answered 2019-10-08 03:12 moys

    Without data it is little tricky. However, can you try the code below?

    df1 = df1[df1.label.isin(df2.label.unique().tolist())]
    df2 = df2[df2.label.isin(df1.label.unique().tolist())]