I have a dataframe df as
Code | Designation |
---|---|
01 | Example 1 |
2F | Example 3 |
40 | Example 10 |
And I have dictionary as
matching = {
'ABCD': ['01','60' ,'YZ'],
'EFG': ['04','2F'],
'007' : ['03','AB' ,'CD', 'DD'],
...
}
I would like to add column on my df base on the matching dictionary as
Code | Designation | Custom 1 |
---|---|---|
01 | Example 1 | ABCD |
2F | Example 3 | EFG |
40 | Example 10 | null |
The lists contain unique value in whole dictionary The matching can return 0 or 1 value
How should I proceed ?
Thank you
CodePudding user response:
Flip matching
then map it over Code
.
_matching_lookup = {e: k for k, v in matching.items() for e in v}
df['Custom 1'] = df['Code'].map(_matching_lookup)
df
Code Designation Custom 1
0 01 Example 1 ABCD
1 2F Example 3 EFG
2 40 Example 10 NaN
CodePudding user response:
As @wjandrea has indicated I would flip the matching dictionary, but if that isn't possible here is a way to accomplish the task leaving matching as it is
import numpy as np
def searchDict(val, dct):
for ky in dct.keys():
if val in dct[ky]:
return ky
return np.nan
df['New_col'] = [searchDict(x, matching) for x in df.index]