Skip to main content
 首页 » 编程设计

python之将 json 数据(未定义/困惑)转换为 DataFrame 的正确方法是什么

2024年11月24日8jirigala

我想了解如何将未正确解析/提取的 JSON 数据转换为 (Pandas) DataFrame。

我正在使用 python (3.7.1) 并尝试了读取 JSON 数据的常用方法。实际上,如果我使用 transpose 或 axis=1 语法,代码就可以工作。但是使用它完全忽略了数据中的大量值或变量,我 100% 确定代码可能正在运行但没有给出预期的结果。

import pandas as pd 
import numpy as np 
import csv 
import json 
sourcefile = open(r"C:\Users\jadil\Downloads\chicago-red-light-and-speed-camera-data\socrata_metadata_red-light-camera-violations.json") 
json_data = json.load(sourcefile) 
#print(json_data) 
type(json_data) 
dict 
## this code works but is not loading/reading complete data 
df = pd.DataFrame.from_dict(json_data, orient="index") 
df.head(15) 
#This is what I am getting for the first 15 rows 
df.head(15) 
0 
createdAt   1407456580 
description This dataset reflects the daily volume of viol... 
rights  [read] 
flags   [default, restorable, restorePossibleForType] 
id  spqx-js37 
oid 24980316 
owner   {'type': 'interactive', 'profileImageUrlLarge'... 
newBackend  False 
totalTimesRated 0 
attributionLink http://www.cityofchicago.org 
hideFromCatalog False 
columns [{'description': 'Intersection of the location... 
displayType table 
indexUpdatedAt  1553164745 
rowsUpdatedBy   n9j5-zh 

请您参考如下方法:

如您所见,即使未正确解析或提取 JSON 数据,Pandas 也会尝试创建数据框。如果您的目标是准确了解 Pandas 在出现困惑的 JSON 文件时会做什么,您可以查看 pd.DataFrame.from_dict() 的代码以了解更多信息。如果您的目标是让 JSON 数据正确转换为 Pandas 数据框,您将需要提供更多关于 JSON 数据的信息,最好是在您的问题中提供数据样本作为文本。如果您的数据足够复杂,您可以尝试使用 json_normalize() 函数,如 here 所述.