Python:json规范化“字符串索引必须为整数"错误 [英] Python: json normalize "String indices must be integers" error

查看:95
本文介绍了Python:json规范化“字符串索引必须为整数"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我收到"TypeError:字符串索引必须为整数"的类型错误.

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

推荐答案

根据

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

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

data : dict or list of dicts Unserialized JSON objects

在上面,pd.read_json返回dataframe. 因此,您可以尝试使用.to_dict()dataframe转换为dictionary.使用 to_dict().

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.

可能类似于以下内容:

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

这篇关于Python:json规范化“字符串索引必须为整数"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆