我从 this web page 下载了一个 .json 文件并使用以下命令转换为字典:
import urllib.request, json
with urllib.request.urlopen("https://www.bcusu.com/svc/voting/stats/election/paramstats/109?groupIds=1,12,7,3,6&sortBy=itemname&sortDirection=ascending") as url:
data = json.loads(url.read().decode())
#print(data)
我的最终目标是将我的数据
(字典)转换为pandas数据框。最主要的是 data
字典是嵌套的,并且让事情变得更复杂的是,有一个嵌套的列(Groups
)。
我找到了this solution它完成“统一”嵌套字典的工作,如下所示:
user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
'Category 2': {'att_1': 23, 'att_2': 'another'}},
15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
'Category 2': {'att_1': 30, 'att_2': 'bar'}}}
“均匀嵌套”是指上面数据框中的外部键和内部键具有相同数量的键:12
和 15
都 两个键 Category 1
和 Category 2
,最后还有两个键 att 1
和 att 2
,我的数据
中并非如此。
最佳答案
当我查看您的数据时,我发现问题来自于组,因此我决定将其隔离并单独处理:
我决定为每个组创建一个数据框:
这是代码:
data_df = {}
for category in data.get('Groups'):
#print(category)
data_df[category.get('Name')] = pd.DataFrame.from_records(category.get('Items'))
这是每个组的输出:
data_df['Faculty']
Eligible IsOtherItem Name NonVoters RelativeTurnout Turnout Voters
0 7249 False Faculty of Business, Law and Social Sciences 5880 4.779694 18.885363 1369
1 6226 False Faculty of Arts, Design and Media 5187 3.627540 16.688082 1039
2 6156 False Faculty of Computing, Engineering and the Buil... 5482 2.353188 10.948668 674
3 8943 False Faculty of Health, Education and Life Sciences 7958 3.439006 11.014201 985
4 71 True Other 56 0.052371 21.126761 15
和年龄范围:
Eligible IsOtherItem Name NonVoters RelativeTurnout Turnout Voters
0 13246 False 18 - 21 10657 9.039173 19.545523 2589
1 6785 False 22 - 25 5939 2.953704 12.468681 846
2 3133 False 26 - 30 2862 0.946163 8.649856 271
3 5392 False Over 30 5024 1.284826 6.824926 368
以及其他团体。
剩下的部分只是信息字典:
del data['Groups']
您可以根据它们或另一个数据框创建一个系列。
如果您知道数据是如何生成的,您可以进行进一步的分析并构建您的 data.frame
关于json - 来自单列中嵌套字典的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52401417/