将json转换为pandas数据帧

问题描述 投票:0回答:2

我有这个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]

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

python json pandas dataframe
2个回答
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
投票

据我所知,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']]
© www.soinside.com 2019 - 2024. All rights reserved.