【问题标题】:Python: json normalize "String indices must be integers" errorPython:json规范化“字符串索引必须是整数”错误
【发布时间】:2019-09-06 16:09:53
【问题描述】:

我在以下代码中收到类型错误“TypeError: string indices must be integers”。

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

【问题讨论】:

  • 你能分享一段你读过的 .json 文件吗?

标签: python json normalization


【解决方案1】:

根据pandas documentation,对于json_normalize方法的data参数:

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

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

可能如下所示:

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

【讨论】:

  • 确实orient="records" 可能有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 2014-04-20
  • 2012-12-11
  • 2021-10-30
  • 2021-09-20
  • 2020-06-18
  • 2020-08-09
相关资源
最近更新 更多