Python: json normalize “String indices must be integers” error

别来无恙 提交于 2020-08-05 04:37:10

问题


I am getting a type error as "TypeError: string indices must be integers" in the following code.

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

回答1:


According to pandas documentation, for data argument of the method json_normalize :

data : dict or list of dicts Unserialized JSON objects

In above, pd.read_json returns dataframe. So, you can try converting dataframe to dictionary using .to_dict(). There are various options for using to_dict() as well.

May be something like below:

json_normalize(full_json_df.to_dict(), ......)


来源:https://stackoverflow.com/questions/55710154/python-json-normalize-string-indices-must-be-integers-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!