Skip to content
Advertisement

How to convert dataframe into dictionary of sets?

I have a dataframe and want to convert a dictionary consists of set.

To be specific, my dataframe and what I want to make it as below:

JavaScript

My goal:

JavaScript

I also wrote a code below, however, I am not sure it is suitable. In reality, the data is large, so I would like to know any tips or other efficient (faster) way to make it.

JavaScript

Advertisement

Answer

Let’s try grouping on the “month’ column, then aggregating by GroupBy.unique:

JavaScript

Or, if you’d prefer a dictionary of sets, use Groupby.agg:

JavaScript

Another idea is to iteratively build a dict (don’t worry, despite using loops this is likely to outspeed the groupby option):

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