I have a pandas dataframe of the following format
User Movie Rating
1 hp1 4
1 hp2 5
2 lor 2
3 sw 2
3 sw2 4
3 sw3 5
I want a dictionary in the format
{ 1 : { hp1:4,hp2:5},
2: { lor:2},
3: { sw:2,sw2:4,sw3:5}
}
I came across few answers like this which deals only with two columns: python pandas dataframe to dictionary
Closest answer is an recursion based approach i found in one of the questions:
def recur_dictify(frame):
if len(frame.columns) == 1:
if frame.values.size == 1: return frame.values[0][0]
return frame.values.squeeze()
grouped = frame.groupby(frame.columns[0])
d = {k: recur_dictify(g.ix[:,1:]) for k,g in grouped}
return d
But when i run this piece of code on a dataframe with million rows then it takes too much time.
I want to know is there a efficient approach to my problem in hand.
Thanks in advance