Skip to content
Advertisement

Group values of a chosen column into a list when creating a dictionary from a pandas data frame with a non-unique index

I have a dataframe that looks like his

JavaScript

I want to get a dictionary structure that looks as follows

JavaScript

I have seen this answer. But it seems like overkill for what I want to do as it converts every value of the key inside the nested dictionary into a list. I would only like to convert col1 into a list when creating the dictionary. Is this possible?

Advertisement

Answer

Use custom lambda function for return unique values in list if there is multiple them else scalar in lambda function:

JavaScript

If order is important use dict.fromkeys for remove duplicates:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement