json - 来自单列中嵌套字典的 Pandas 数据框

标签 json python-3.x pandas dictionary

我从 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'}}}

“均匀嵌套”是指上面数据框中的外部键和内部键具有相同数量的键:1215 两个键 Category 1Category 2,最后还有两个键 att 1att 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/

相关文章:

python - 是否可以创建一个既没有 __slots__ 也没有 __dict__ 的 python 对象?

python - 查找没有有限值的 Pandas 数据框的行索引

python - Pandas:使用模式从列中提取和选择数据

javascript - 通过删除 javascript 中的重复项来组合对象数组

javascript - 上传到服务器时,笔 (codepen) 不工作

python - 除非通过 CMD 输入,否则无法从 python 控制台导入模块

python - 在 Pandas 的 str 数据框中查找多列的平均值

javascript - JSON.stringify 和 "\u2028\u2029"检查?

json - 配置 vscode json 格式化空间

python - 循环运行 label_image.py