将json转换为pandas数据帧

时间:2017-12-27 13:31:08

标签: python json pandas dataframe

我有这个json数据:

{
  "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"
    ]
  ]
}

我试图以这种格式(时间序列)进入熊猫数据框:

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

我试过了:

t = pd.read_json(q)

但是这给了我:

                     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]

我怎样才能把它变成正确的格式?

2 个答案:

答案 0 :(得分:2)

如果两个列的时间相同,在读完json后我们可以选择值并连接它们:

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

答案 1 :(得分:1)

据我所知,read_json()中没有选项可以做到这一点。我的建议是在您阅读数据后重新使用表格。

 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']]