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

Extracting a mapping from a pandas dataframe

I have a dataframe with two columns labelId and type. There are many entries with the same labelId, but given a labelId its type is unique. I want to extract this mapping from labelId to type as a dict. What is the best way to do this?

For the dataframe below:

Values labelId Type
1 First high
5 First high
2 Second low

The expected dict is {'First': 'high', 'Second': 'low'}.

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

>Solution :

here is one way to do it,
drop the duplicates on labelId and type, then choose same columns
and extract as dict

dict(df.drop_duplicates(subset=['labelId','Type'])[['labelId','Type']].values)

OR
as Abhilash improved on it

dict(df[['labelId','Type']].drop_duplicates().values)
{'First ': 'high', 'Second ': 'low'}
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