Pandas - Get the corresponding value from dictionary while comparing

I have a dictionary (not a dataframe) like this,

Emp ID  dictvalue
1        True
2        False

And I have a dataframe like this,

  Emp ID    ColA       ColB
     1          A         B
     2          A         A 

I am doing a compare between ColA and ColB

temp_result_df[res_col_name] = (temp_result_df[primaryreportreqcolname] == temp_result_df[RequiredSecondaryReport_Col_Name])

I am looking for an or logic in the code, that will have the dictvalue (Boolean true or false) from the dictionary by mapping with the empid. It will be a lot easier for me, if it is on the same line of code for my convenient maintenance.

Something like,

temp_result_df[res_col_name] = (temp_result_df[primaryreportreqcolname] == temp_result_df[RequiredSecondaryReport_Col_Name]) | ??...dictvalue......??

I don't want to add dict as a new column to this temp_result_df at this point. Converting the dictionary to a dataframe and doing a join will be an easy solution. But, I will have to drop that column again and the next operations will become messier as this is present in multiple places.

The expected result,

  Emp ID    ColA       ColB   result
     1          A         B    True
     2          A         A    True

The Emp ID 1 returns a False while comparing ColA and ColB but on OR logic with the dictvalue coming from the dataframe, it becomes a True.

Upvotes: 1

Views: 40

Answers (1)

jezrael
jezrael

Reputation: 862541

Use map chained with bitwise OR:

d = {1:True, 2:False}

df['result'] = (df['ColA'] == df['ColB']) | df['Emp ID'].map(d)
print (df)
   Emp ID ColA ColB  result
0       1    A    B    True
1       2    A    A    True

Detail:

print (df['ColA'] == df['ColB'])
0    False
1     True
dtype: bool

print (df['Emp ID'].map(d))
0     True
1    False
Name: Emp ID, dtype: bool

Upvotes: 2

Related Questions