我从美国宾夕法尼亚州的一个选举网站上抓取了一个样本,下面是从该网站的json中得到的嵌套字典:
some_dict = {'Election': {'Statewide': [{'ADAMS': [{'CandidateName': 'BIDEN, JOSEPH '
'ROBINETTE JR',
'CountyName': 'ADAMS',
'ElectionDayNoVotes': '0',
'ElectionDayVotes': '1',
'ElectionDayYesVotes': '0',
'ElectionYear': '2020'
},
{'CandidateName': 'TRUMP, DONALD J. ',
'CountyName': 'ADAMS',
'ElectionDayNoVotes': '0',
'ElectionDayVotes': '1',
'ElectionDayYesVotes': '0',
'ElectionYear': '2020'
}],
'ALLEGHENY': [{'CandidateName': 'BIDEN, JOSEPH '
'ROBINETTE JR',
'CountyName': 'ALLEGHENY',
'ElectionDayNoVotes': '0',
'ElectionDayVotes': '1',
'ElectionDayYesVotes': '0',
'ElectionYear': '2020'
},
{'CandidateName': 'TRUMP, DONALD '
'J. ',
'CountyName': 'ALLEGHENY',
'ElectionDayNoVotes': '0',
'ElectionDayVotes': '1',
'ElectionDayYesVotes': '0',
'ElectionYear': '2020'
}]}]}}
我不知道如何将其转换为如下所示的数据帧:
解决方案
您可以使用以下两种方法中的任意一种进行此操作:
pd.read_json()
pd.DataFrame()
.DataFrame()
方法接受a
single dict
键是列名,值是列值
a
list of dicts
每个列表项都是数据帧的一行,以
dict
表示:键是该特定行的列名和列值代码
这里,我们使用
list of dicts
方法来创建数据帧。首先,我们使用自定义函数prepare_records()
将数据转换为list of dicts
,然后应用以下两种方法之一输出:
自定义函数
虚拟数据
相关问题 更多 >
编程相关推荐