0

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?

1 Answers1

-1

Possibly using to_json on the dataframe? See here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html

Brandy
  • 149
  • 2
  • 14
  • to_json, as far as I understand, cannot use VALUES as keys, only columns. – thatOldITGuy Aug 19 '21 at 21:59
  • I thought you might be able to use the orient parameters. I found this that might be helpful (different than your links above)? https://stackoverflow.com/questions/40470954/convert-pandas-dataframe-to-nested-json/ – Brandy Sep 07 '21 at 16:08