Skip to content
Advertisement

df.to_dict make duplicated index (pandas) as primary key in a nested dict

I have this data frame which I’d like to convert to a dict in python, I have many other categories, but showed just two for simplicity

JavaScript

I want the output to be like this

JavaScript

Advertisement

Answer

You can do this without assigning an additional column or aggregating using list:

JavaScript

I created a separate function for readability – you could, of course, pass it as a lambda too:

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