0

I have the following Pandas pivot

Apple    Green    5
         Red      3
         Yellow   4
Grapes   Red      1
         Green    3

and want to convert this data to JSON like follows:

{
    Apple: {
            Green : 5, 
            Red:    3, 
            Yellow: 4,
            },
    Grapes:{ 
            Red :   1, 
            Green:  3 
            }
}

How do I accomplish this? I have tried to_json(), which returns a different format.

1 Answers1

0

The DataFrame.to_json has several parameters for the orientation of the JSON.

Try something like pd.to_json(orient='records'), if it does not work, check the others values of the orient variable in http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.to_json.html

Rednaxel
  • 938
  • 2
  • 16
  • 33
  • I have tried all 4 values for the orient parameter, and none produce the JSON format I've described above – Homan Mohammadi Jan 27 '16 at 03:59
  • Try to use pd.melt to change the DataFrame structure and then execute the to_json with the result. http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html – Rednaxel Jan 27 '16 at 04:05