warrenfitzhenry
warrenfitzhenry

Reputation: 2299

convert json into pandas dataframe

I have this json data:

{
  "current": [
    [
      0,
      "2017-01-15T00:08:36Z"
    ],
    [
      0,
      "2017-01-15T00:18:36Z"
    ]
  ],
  "voltage": [
    [
      12.891309987,
      "2017-01-15T00:08:36Z"
    ],
    [
      12.8952162966,
      "2017-01-15T00:18:36Z"
    ]
  ]
}

and I am trying to get into it into a pandas dataframe in this format (time series):

time                  current      voltage
2017-01-15T00:08:36Z    0         12.891309987
2017-01-15T00:18:36Z    0         12.8952162966

I have tried:

t = pd.read_json(q)

but this gives me:

                     current                                voltage
0  [0, 2017-01-15T00:08:36Z]   [12.891309987, 2017-01-15T00:08:36Z]
1  [0, 2017-01-15T00:18:36Z]  [12.8952162966, 2017-01-15T00:18:36Z]

how can I get this into the correct format?

Upvotes: 0

Views: 352

Answers (2)

felix the cat
felix the cat

Reputation: 165

To my knowledge there is not option in read_json() to do that. My suggestion would be to re-work the table once you read the data.

 t = pd.read_json('data.json')
 t['time'] = [x[1] for x in t['current']]
 t['current'] = [x[0] for x in t['current']]
 t['voltage'] = [x[0] for x in t['voltage']]

Upvotes: 1

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

If both the columns time is same, aftering reading json we can select the values and concat them :

ndf = pd.read_json(q)

ndf = pd.concat([ndf.apply(lambda x : x.str[0]),ndf['current'].str[1].rename('time')],1)

   current    voltage                  time
0        0  12.891310  2017-01-15T00:08:36Z
1        0  12.895216  2017-01-15T00:18:36Z

Upvotes: 2

Related Questions