我在以下代码中收到“ TypeError:字符串索引必须为整数”的类型错误。
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
:
data:字典或字典列表未序列化的JSON对象
在上面,pd.read_json
返回dataframe
。所以,你可以尝试转换dataframe
到dictionary
使用.to_dict()
。也有多种使用to_dict()的选项。
可能如下所示:
json_normalize(full_json_df.to_dict(), ......)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句