It's very similar to this and this, but still different enough to not be applicable
I have a dataframe like this:
df = pd.DataFrame(data=[['u1', 't1', 1], ['u1', 't2', 1], ['u2', 't1', 0]],
columns=['user', 'track', 'rel'])
I need to produce the following JSON:
{ 'u1' : {
't1' : 1,
't2' : 1
},
'u2' : {
't1' : 0
}
}
- Column names are not important
- There can be no array sign "[" in results.
I've tried
a = [{ k : [{t : 1} for t in g['track']]} for k, g in df.groupby('user')]
json.dumps(a)
The result is almost what I want, but with undesired brackets and values are not grouped properly:
'[{'u1': [{'t1': 1}, {'t2': 1}, {'t1': 1}]},
{'u2': [{'t1': 1}, {'t2': 1}, {'t1': 1}]}]'
Is there a efficient way to accomplish this?