【发布时间】:2018-03-25 16:37:44
【问题描述】:
我想在 python 中使用 pandas 和 json_normalize 规范化 JSON 数据。 下面代码中的第 33 行工作正常。在第 36 行,我将最后一个元素更改为“数字”并收到以下错误消息:
Traceback (most recent call last):
File "/Users/Home/Downloads/JSONtoCSV/testflattening.py", line 32, in <module>
print json_normalize(data, 'items', [['address','city'], ['address','company_name'], 'number'])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/json/normalize.py", line 262, in json_normalize
'need distinguishing prefix ' % k)
ValueError: Conflicting metadata name number, need distinguishing prefix
我认为这是因为项目“数字”与熊猫的内部变量冲突。所以我需要将所有“数字”项目重命名为其他名称。
我在第一种方法中使用下面第 28 行中的代码进行了尝试,但我收到了错误消息:
ValueError: 'number' is not in list
抱歉,我对 python 完全陌生——我做错了什么?
谢谢!
import pandas
from pandas.io.json import json_normalize
data = [{'address': {
'city': 'city A',
'company_name': 'company A'},
'amount': 998,
'items': [{'description': 'desc A1','number': 'number A1'}],
'number': 'number of A',
'service_date': {
'type': 'DEFAULT',
'date': '2015-11-18'},
'vat_option': 123},
{'address': {
'city': 'city B',
'company_name': 'company B'},
'amount': 222,
'items': [{'description': 'desc B1','number': 'number B1'},
{'description': 'desc B2','number': 'number B2'}],
'number': 'number of B',
'service_date': {
'type': 'DEFAULT',
'date': '2015-11-18'},
'vat_option': 456}
]
data[data.index("number")] = "numbr"
print data
# working
#print json_normalize(data, 'items', [['address','city'], ['address','company_name'], 'amount'])
# not working
#print json_normalize(data, 'items', [['address','city'], ['address','company_name'], 'numbr'])
【问题讨论】: