我在以下代码中收到类型错误为"类型错误:字符串索引必须是整数"。
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)
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
根据 pandas 文档,对于方法data
参数json_normalize
:
数据:字典或字典列表 未序列化的 JSON 对象
在上面,pd.read_json
返回dataframe
。因此,您可以尝试使用 .to_dict()
将dataframe
转换为dictionary
。使用 to_dict(( 也有各种选项。
可能如下所示:
json_normalize(full_json_df.to_dict(), ......)