代码之家  ›  专栏  ›  技术社区  ›  P. Prunesquallor

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

  •  0
  • P. Prunesquallor  · 技术社区  · 8 年前

    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

    3 回复  |  直到 8 年前
        1
  •  1
  •   Amadan    8 年前

    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)
    
        2
  •  0
  •   zipa    8 年前

    代码运行得很好,但是 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}]}]
    

    这是一个只有一条记录的示例。

        3
  •  0
  •   P. Prunesquallor    8 年前

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