pandasrowisin

How to compare rows within the same dataframe and create a new column for similar rows


obj_id Column B Colunm C
a1 cat bat
a2 bat man
r1 man apple
r2 apple cat

The orignal dataframe (above) is called df

I am trying to make a new colunm called new_obj_id where if rows in column B match any row of col C the new_obj_id should then have values of obj_id that match col B

obj_id Column B Colunm C new_obj_id
a1 cat bat a2
a2 bat man r1
r1 man apple r2
r2 apple cat a1

This is the expected table

This is what I tried but couldn't get through:

dataframe1['new_obj_id'] = dataframe1.apply(lambda x: x['obj_id'] 
                           if x['Column_B'] in x['Column C']
                           else 'none', axis=1)

Solution

  • Try this:

    df['new_obj_id'] = df['Column C'].map(dict(zip(df['Column B'],df['obj_id'])))
    

    Output:

    0    a2
    1    r1
    2    r2
    3    a1