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一书中的一个例子
for rec in db
迭代列名。要遍历行,
for id, rec in db.iterrows():
fnuts = pd.DataFrame(rec["nutrients"])
fnuts["id"] = rec["id"]
nutrients.append(fnuts)
虽然这有点慢(所有需要构建的字典)。itertuples
是比较快的; 但由于您只关心两个系列,直接迭代系列可能是最快的:
for id, value in zip(db['id'], db['nutrients']):
fnuts = pd.DataFrame(value)
fnuts["id"] = id
nutrients.append(fnuts)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句