Python:json规范化“字符串索引必须是整数”错误

She*_*abu 5 python json normalization

我在以下代码中收到类型错误,如“类型错误:字符串索引必须为整数”。

import pandas as pd 
import json
from pandas.io.json import json_normalize

full_json_df = pd.read_json('data/world_bank_projects.json')
json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
json_nor.groupby('name')['code'].count().sort_values(ascending=False).head(10)
Run Code Online (Sandbox Code Playgroud)
Output:
TypeError                                 
Traceback (most recent call last)
<ipython-input-28-9401e8bf5427> in <module>()
      1 # Find the top 10 major project themes (using column 'mjtheme_namecode')
      2 
----> 3 json_nor = json_normalize(full_json_df, 'mjtheme_namecode')
      4 #json_nor.groupby('name')['code'].count().sort_values(ascending = False).head(10)
TypeError: string indices must be integers
Run Code Online (Sandbox Code Playgroud)

stu*_*ent 7

根据pandas 文档data该方法的参数json_normalize

data :字典或字典列表未序列化的 JSON 对象

在上面,pd.read_json返回dataframe. 因此,您可以尝试转换dataframedictionary使用.to_dict(). 使用to_dict()也有多种选项。

可能类似于下面的内容:

json_normalize(full_json_df.to_dict(), ......)
Run Code Online (Sandbox Code Playgroud)