Skip to content
Advertisement

GroupBy results to list of dictionaries, Using the grouped by object in it

My DataFrame looks like so:

JavaScript

And I’m looking to group it by Date and extract that data to a list of dictionaries so it appears like this:

JavaScript

This is my code so far:

JavaScript

Using this method can’t use my grouped by objects in the apply method itself:

JavaScript

Using to_dict() giving me the option to reach the grouped by object, but not to parse it to the way I need.

Anyone familiar with some elegant way to solve it?

Thanks!!

Advertisement

Answer

You could first reshape your data using df.pivot, reset the index, and then apply to_dict to the new shape with the orient parameter set to “records”. So:

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