pythonjsonpandasdataframeto-json

Pandas dataframe to json with format {column1 name : [Values], column2 name: [values], Column3 name... }


I'm new in python and pandas. I'm trying to convert a pandas dataframe to a json with format:

{column1 name : [Values], column2 name: [values], Column3 name... }

I've trying using:

df.to_json(orient='columns')

with this option I get something line

{"Col1 name":{"row key1": value1, "row key2": value2}, "Col2 name":{"row key1": value1, "row key2": value2}}

I'll be very grateful if someone can help me or give an idea on how to convert the dataframe and obtain the format without the rows keys.

As reference my dataframe looks like:

      date       batch          result            LSL            USL    target
0    2010-01-16  00154354A0     1100.0           680.0          1210.0  1100.0
1    2010-01-16  00164354A2     1070.0           680.0          1210.0  1100.0

And what I want to achieve is:

{'date':['2010-01-16', '2010-01-16'], 'batch': ['00154354A0', '00164354A2'], 'result':[1100.0, 1070.0], 'LSL':...}

Many thanks in advance


Solution

  • Try this:

    In [1773]: df.to_dict(orient='list')
    Out[1773]: 
    {'date': ['2010-01-16', '2010-01-16'],
     'batch': ['00154354A0', '00164354A2'],
     'result': [1100.0, 1070.0],
     'LSL': [680.0, 680.0],
     'USL': [1210.0, 1210.0],
     'target': [1100.0, 1100.0]}