首页 > 解决方案 > 当我尝试使用 python pandas 模块将 json 转换为数据框时出现 ValueError

问题描述

我有一个嵌套的 json。我正在尝试将此 json 转换为 pandas 中的数据框

import json
import pandas as pd

with open('scratch.json') as f:
    data = json.load(f)

df = pd.DataFrame(data)

print(df)

我得到以下错误

Traceback (most recent call last):
  File "/Users/nitesh/Library/Preferences/PyCharmCE2019.3/scratches/nitesh.py", line 8, in <module>
    df = pd.DataFrame(data)
  File "/Users/nitesh/.local/share/virtualenvs/nitesh-ovXpZdv7/lib/python3.7/site-packages/pandas/core/frame.py", line 435, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "/Users/nitesh/.local/share/virtualenvs/nitesh-ovXpZdv7/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 254, in init_dict
    return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
  File "/Users/nitesh/.local/share/virtualenvs/nitesh-ovXpZdv7/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 64, in arrays_to_mgr
    index = extract_index(arrays)
  File "/Users/nitesh/.local/share/virtualenvs/nitesh-ovXpZdv7/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 365, in extract_index
    raise ValueError("arrays must all be same length")
ValueError: arrays must all be same length

如何将嵌套的json转换为数据框

标签: pythonjsonpandas

解决方案


推荐阅读