无法访问pandas系列中存储的嵌套JSON字段

2024-09-28 03:18:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我要完成的目标是对“mjtheme_namecode”列中任何数字出现的次数进行“计数”。我的导师说我们必须使用json\u normalize方法来完成这个任务。在

通常我会用pd.value_计数()但单元格中有其他文本,因此这是不可能的。在

格式如下:

enter image description here

我用过pd.read_json文件将数据读入pandas数据帧,然后在列mjtheme_namecode上进行过滤。我尝试过使用json\u normalize访问数据,但仍然出现错误:“字符串索引必须是整数”。在

sample = df.to_json #Convert series to a json string
json_normalize(sample2, 'name')

有人能指出我如何解决这个问题吗?在

谢谢你!在


Tags: to数据方法json目标value数字次数
1条回答
网友
1楼 · 发布于 2024-09-28 03:18:01

对我来说:

import json
from pandas.io.json import json_normalize

with open('world_bank_projects.json') as data_file:    
    data = json.load(data_file)  

df = json_normalize(data, 'mjtheme_namecode')
print (df.head())
  code                                   name
0    8                      Human development
1   11                                       
2    1                    Economic management
3    6  Social protection and risk management
4    5                  Trade and integration

相关问题 更多 >

    热门问题