【问题标题】:Reading JSON (with nested arrays) in Pandas在 Pandas 中读取 JSON(带有嵌套数组)
【发布时间】:2021-03-27 21:34:24
【问题描述】:

我正在尝试加载 JSON 文件 message_1.json,其数据结构如下所示:

{
  "participants": [
    {
      "name": "X"
    },
    {
      "name": "Y"
    }
  ],
  "messages": [
    {
      "sender_name": "X",
      "timestamp_ms": 1608148658236,
      "content": "Hi",
      "type": "Generic"
    },
    {
      "sender_name": "Y",
      "timestamp_ms": 1608148604578,
      "content": "Hey",
      "type": "Generic"
    },
    {
      "sender_name": "X",
      "timestamp_ms": 1608148599875,
      "content": "Bye",
      "type": "Generic"
    },

    ...
    ...
    ...

我使用了df = pd.read_json("message_1.json"),结果为ValueError: arrays must all be same length。

我相信here 也有人问过类似的问题,我已经尝试使用指定的解决方案

with open('message_1.json') as json_data:
    data = json.load(json_data) # Data is successfully loaded here in the above format

pd.DataFrame.from_dict(data, orient='timestamp_ms').T.set_index('timestamp_ms') 

由于数据中没有index 列,我将索引设置为timestamp_ms 导致错误ValueError: only recognize index or columns for orient

我认为我以错误的方向加载了 JSON。

请指教。

【问题讨论】:

  • 请发布预期的输出数据框

标签: python json pandas


【解决方案1】:

从 json-input 来看,您似乎只想要保留“消息”部分。

import json
import pandas as pd

with open('message_1.json') as json_data:
    data = json.load(json_data)

messages = data['messages']

# messages is a list, not a dict
df = pd.DataFrame(messages)

df.set_index('timestamp_ms', inplace=True)

输出:

              sender_name content     type
timestamp_ms                              
1608148658236           X      Hi  Generic
1608148604578           Y     Hey  Generic
1608148599875           X     Bye  Generic

【讨论】:

  • 正是我正在寻找的答案。谢谢!
猜你喜欢
  • 2020-07-29
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2020-07-21
  • 2021-06-24
  • 2020-05-20
  • 1970-01-01
  • 2018-04-28
相关资源
最近更新 更多