Home > database >  Check if dictionaries are equal in df
Check if dictionaries are equal in df

Time:03-24

I have a df, in which a column contains dictionaries:

      a    b    c   d
0     a1   b1   c1  {0.0: 'a', 1.0: 'b'}
1     a2   b2   c2  NaN
2     a3   b3   c3  {0.0: 'cs', 1.0: 'ef', 2.0: 'efg'}

and another dict:

di = {0.0: 'a', 1.0: 'b'}

I want to add a new column with 'yes' in it when d=di, and 'no' or 'NaN' or just empty when it's not. I tried the below but it doesnt work:

df.loc[df['d'] == di, 'e'] = 'yes'

The result would be:

      a    b    c   d                                    e
0     a1   b1   c1  {0.0: 'a', 1.0: 'b'}                 yes
1     a2   b2   c2  NaN
2     a3   b3   c3  {0.0: 'cs', 1.0: 'ef', 2.0: 'efg'}

Anyone being able to help me here? Thank you in advance!

CodePudding user response:

You can try

df['new'] = df['d'].eq(di).map({True:'yes',False:''})
  • Related