【发布时间】:2023-03-31 04:46:01
【问题描述】:
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}
...
]
}
以下是书中练习的代码*。它包括一些争吵,并将每种食物的营养成分组合到一张大桌子中:
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 Traceback (most recent call last)
<ipython-input-23-ac63a09efd73> in <module>()
1 for rec in db:
----> 2 fnuts = pd.DataFrame(rec["nutrients"])
3 fnuts["id"] = rec["id"]
4 nutrients.append(fnuts)
5
TypeError: string indices must be integers
*这是本书Python for Data Analysis中的一个例子
【问题讨论】:
-
您的 JSON 无效(即使更正引号并删除点,
pd.read_json也无法加载它)。请提交我们可以实际看到您的问题的数据。 -
@Amadan,这里是数据的链接:github.com/wesm/pydata-book/blob/master/ch07/…
标签: python json pandas typeerror