以下是我的json文件的子集:
d = {'data': {'questions': [{'id': 6574,
'text': 'Question #1',
'instructionalText': '',
'minimumResponses': 0,
'maximumResponses': None,
'sortOrder': 1,
'answers': [{'id': 362949, 'text': 'Answer #1', 'parentId': None},
{'id': 362950, 'text': 'Answer #2', 'parentId': None},
{'id': 362951, 'text': 'Answer #3', 'parentId': None},
{'id': 362952, 'text': 'Answer #4', 'parentId': None}]}]}}
我想把它放在一个数据框中,每个问题都有一行,每个答案都有一行
Python代码:
from pandas import json_normalize
import json
fields = ['text','answers.text']
with open(R'response.json') as f:
d = json.load(f)
data = json_normalize(d['data'],['questions'],errors='ignore')
data = data[fields]
print(data)
这会产生一个键错误:
KeyError: "['answers.text'] not in index"
我已经在这里呆了几个小时了,但完全无法理解这一点。我觉得应该很简单,但从来都不是
record_prefix
,与record_path
和meta
一起使用,这样d
可以一次全部规范化record_path
和meta
之间存在重叠的key
名称时,{a1}将导致ValueError
,并且'id'
和'text'
都在这两个名称中李>ValueError: Conflicting metadata name id, need distinguishing prefix
在不使用record_path
的情况下发生李>KeyError
是因为'answers.text'
不在d
中,它是由.json_normalize()
创建的keys
在df
中不是必需的,请将它们从meta
中删除李>扩展测试数据
.apply(pd.Series)
,因为它非常慢。这是我通常使用的技术
json_normalize()
顶级列表explode()
子list
,reset_index()
步骤#3apply(pd.Series)
展开子list
中的dict
相关问题 更多 >
编程相关推荐