Pandas data frame from nested dictionary in a single column

时间:2018-09-19 08:26:43

标签: json python-3.x pandas dictionary

I have downloaded a .json file from this web page and converted into a dictionary with the following commands:

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)

My final goal is to convert my data, which is a dictionary into a pandas data frame. The main thing is that the data dictionary is nested and, to complicate things a bit further, there is a single column (Groups) which is nested.

I have found this solution which does the job for a 'uniformly' nested dictionary which looks like the following:

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

By 'uniformly nested' I mean that the outer and inner keys in the dataframe above have all the same number of keys: 12 and 15 have both two keys Category 1 and Category 2, which, finally, also have two keys att 1 and att 2, which is not the case in my data.

1 个答案:

答案 0 :(得分: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']

您可以从它们或另一个数据框中创建一个意向。

如果您知道数据是如何生成的,则可以进行进一步的分析并构建数据。