Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New column in pandas dataframe from dictionary with lists as values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading