Extracting a mapping from a pandas dataframe

Question:

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'}.

Asked By: Abhilash

||

Answers:

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'}
Answered By: Naveed
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.