将字典转换为数据框作为python中的预期输出
Posted
技术标签:
【中文标题】将字典转换为数据框作为python中的预期输出【英文标题】:converting dictionary into dataframe as expected output in python 【发布时间】:2021-08-27 01:01:08 【问题描述】:假设我有一本字典
dj=
"totalrecords": 2,
"data": [
"stateCd": "U.K",
"stateName": "uttarakhand",
"details":
"id": [
"2312-k",
"2312-k"
],
"date": [
"10-OCT-2019",
"11-OCT-2019"
],
"icp": [
2233,
6443
],
"icpr": [
3.434,
23.232
]
,
"stateCd": "U.P",
"stateName": "uttar pradesh",
"details":
"id": [
"2712-k",
"5412-k"
],
"date": [
"10-OCT-2019",
"11-OCT-2019"
],
"icp": [
2233,
6443
],
"icpr": [
32.434,
31.232
]
]
我想将此 json/dictionary 转换为使用 python 的数据框:
但我不知道如何执行此操作
我也试过pandas.json_normalize()
但在输出中没有得到我预期的列,即 date,icp,icpr
data_trunc=dj['data']
pd.json_normalize(data_trunc,record_path=['details','id'],meta=['stateCd','stateName'])
enter image description here
【问题讨论】:
您将pandas
列为您的标签之一,您能告诉我们您的尝试吗?如果您不知道如何开始,也许您可以先看一个将 dict 转换为数据框的教程,例如datatofish.com/dictionary-to-dataframe
我尝试了什么 print(response) print(type(response)) dict_trunc = response['data'][0] new = pd.DataFrame.from_dict(dict_trunc) print(new)跨度>
连同它我也尝试了“flatten-json”,但它没有得到 expeted 输出
【参考方案1】:
你可以试试这样的
Reference
data = ['state': 'Florida',
'shortname': 'FL',
'info': 'governor': 'Rick Scott',
'counties': ['name': 'Dade', 'population': 12345,
'name': 'Broward', 'population': 40000,
'name': 'Palm Beach', 'population': 60000],
'state': 'Ohio',
'shortname': 'OH',
'info': 'governor': 'John Kasich',
'counties': ['name': 'Summit', 'population': 1234,
'name': 'Cuyahoga', 'population': 1337]]
result = pd.json_normalize(data, 'counties', ['state', 'shortname',
['info', 'governor']])
输出:
0 Dade 12345 Florida FL Rick Scott
1 Broward 40000 Florida FL Rick Scott
2 Palm Beach 60000 Florida FL Rick Scott
3 Summit 1234 Ohio OH John Kasich
4 Cuyahoga 1337 Ohio OH John Kasich
【讨论】:
这很好!熊猫很有用。只需 1 行代码,你就做到了哇!我对熊猫一无所知 从realpython查看熊猫的相关文章。必须有其他更好的资源来学习熊猫。这是我用的那个 @SomeshwaranS 我试过 pandas.json_normalize() 作为 pd.json_normalize(data_trunc,record_path=['details','id'],meta=['stateCd','stateName']) 但是没有得到我预期的输出,你能帮忙吗 是否可以将details
对象编辑为像details = ['id': '2312-k','icp':'2233','icpr':'3.434','date':'10-OCT-2019','id': '2312-k','icp':'6443','icpr':'23.232','date':'11-OCT-2019']
这样的字典列表【参考方案2】:
也许这可以帮助你:-
import json
f = open('1.json')
file = json.load(f)
for data in file['data']:
stCd = data['stateCd']
stateN = data['stateName']
date = data['details']['date']
icp = data['details']['icp']
icpr = data['details']['icpr']
full = f"StCd StateName Date ICP ICPR"
whole = f"stCd stateN date[0] icp[0] icpr[0]"
whole2 = f"stCd stateN date[1] icp[1] icpr[1]"
print()
print(full)
print(whole)
print(whole2)
输出:-
StCd StateName Date ICP ICPR
U.K uttarakhand 10-OCT-2019 2233 3.434
U.K uttarakhand 11-OCT-2019 6443 23.232
StCd StateName Date ICP ICPR
U.P uttar pradesh 10-OCT-2019 2233 32.434
U.P uttar pradesh 11-OCT-2019 6443 31.232
【讨论】:
以上是关于将字典转换为数据框作为python中的预期输出的主要内容,如果未能解决你的问题,请参考以下文章