Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-TypeError解析JSON时:字符串索引必须是整数_Python_Json_Pandas_Typeerror - Fatal编程技术网

python-TypeError解析JSON时:字符串索引必须是整数

python-TypeError解析JSON时:字符串索引必须是整数,python,json,pandas,typeerror,Python,Json,Pandas,Typeerror,JSON文件中的记录如下所示(请注意“营养素”是什么样子的): 以下是本书练习*中的代码。它包括一些争论,并将每种食物的营养素组合成一张大桌子: import pandas as pd import json db = pd.read_json("foods-2011-10-03.json") nutrients = [] for rec in db: fnuts = pd.DataFrame(rec["nutrients"]) fnuts["id"] = rec["i

JSON文件中的记录如下所示(请注意“营养素”是什么样子的):

以下是本书练习*中的代码。它包括一些争论,并将每种食物的营养素组合成一张大桌子:

import pandas as pd
import json

db = pd.read_json("foods-2011-10-03.json")

nutrients = []

for rec in db:
     fnuts = pd.DataFrame(rec["nutrients"])
     fnuts["id"] = rec["id"]
     nutrients.append(fnuts)
但是,我得到了以下错误,我无法找出原因:


TypeError回溯(最近一次调用)
在()
1对于数据库中的rec:
---->2 fnuts=pd.数据帧(rec[“营养素”])
3 fnuts[“id”]=rec[“id”]
4.添加营养素(fnuts)
5.
TypeError:字符串索引必须是整数

*这是本书中的一个例子,代码运行得非常好,但是
json
应该是这样的代码:

[{
"id": 21441,
"description": "KENTUCKY FRIED CHICKEN, Fried Chicken, EXTRA CRISPY,Wing, meat and skin with breading",
"tags": ["KFC"],
"manufacturer": "Kentucky Fried Chicken",
"group": "Fast Foods",
"portions": [
{"amount": 1,
"unit": "wing, with skin",
"grams": 68.0}],
"nutrients": [{
"value": 20.8,
"units": "g",
"description": "Protein",
"group": "Composition"
},
{'description': 'Total lipid (fat)',
'group': 'Composition',
'units': 'g',
'value': 29.2}]}]

这是一个仅包含一条记录的示例。

for rec in db
迭代列名。要在行上迭代

for id, rec in db.iterrows():
    fnuts = pd.DataFrame(rec["nutrients"])
    fnuts["id"] = rec["id"]
    nutrients.append(fnuts)
不过这有点慢(所有需要构造的dict)<代码>itertuples更快;但由于您只关心两个系列,直接迭代系列可能是最快的:

for id, value in zip(db['id'], db['nutrients']):
    fnuts = pd.DataFrame(value)
    fnuts["id"] = id
    nutrients.append(fnuts)

阿马丹回答了这个问题,但在看到他的答案之前,我设法解决了这个问题:

for i in range(len(db)):
    rec = db.loc[i]
    fnuts = pd.DataFrame(rec["nutrients"])
    fnuts["id"] = rec["id"]
    nutrients.append(fnuts)

您的JSON无效(即使更正引号并删除点,也无法通过
pd.read\u JSON
加载)。请提交数据,我们可以在上面看到您的问题。@Amadan,以下是数据链接:谢谢,效果很好!自从这本书写完后,这个迭代的工作方式有没有变化,或者应该添加到书的勘误表中?对不起,我对熊猫的历史了解不多,我也没有读过这本书。
for id, value in zip(db['id'], db['nutrients']):
    fnuts = pd.DataFrame(value)
    fnuts["id"] = id
    nutrients.append(fnuts)
for i in range(len(db)):
    rec = db.loc[i]
    fnuts = pd.DataFrame(rec["nutrients"])
    fnuts["id"] = rec["id"]
    nutrients.append(fnuts)