I have a dataframe:
df = pd.DataFrame({'col1': [111, 333, 456]})
And I have a dictionary with keys that correspond to a category and values with the type list.
dct = {'A': [111, 222, 333, 444], 'B': [123, 456, 789]}
The values in the list may or may not be found in col1. I’d like to create col2 that would return the key from dct.
My desired output is this:
col1 | col2
-------+---------
111 | A
333 | A
456 | B
I’ve tried df['col2'] = df['col1'].map(dct) but this returns NaN values.
>Solution :
You can try with:
df['col2'] = df['col1'].map(lambda x: [key for key in dct if x in dct[key]][0])
Returning:
col1 col2
0 111 A
1 333 A
2 456 B