[英]Turn pandas dataframe into dictionary
I am running a for loop over a pandas dataframe that takes each row and creates a dictionary (of a sort) then uploads to an internal system.我在 pandas dataframe 上运行 for 循环,该循环获取每一行并创建一个字典(某种)然后上传到内部系统。
The for loop isn't a problem, neither is the upload to the internal system. for 循环不是问题,上传到内部系统也不是问题。 I cannot seem to get the format of the dictionary correct for the upload to proceed.
我似乎无法获得正确的字典格式以进行上传。
Here is a model of the dataframe:这是 dataframe 的 model:
Id Acct_num Acct_Name Prod Date Rev
0 1495 5001 Alpha ret34 4/30/2020 4999
1 1496 5002 Beta pro45 4/30/2020 18076
2 1497 5003 Gamma sli55 4/30/2020 5671
3 1498 5004 Delta ret34 4/30/2020 16683
for better viewing if needed如果需要,可以更好地查看
I need each row of the dataframe to look like the below (first two rows):我需要 dataframe 的每一行如下所示(前两行):
1495:{'Acct_num':'5001', 'Acct_Name':'Alpha', 'Prod':'ret34', 'Date':'4/30/2020', 'Rev':'4999'}
1496:{'Acct_num':'5002', 'Acct_Name':'Beta', 'Prod':'pro45', 'Date':'4/30/2020', 'Rev':'18076'}
Here is what I have tried (with a few other variations, but to no avail):这是我尝试过的(还有其他一些变化,但无济于事):
for row in df.iloc[:,:].itertuples(index=False):
if not row:
break
else:
d = row._asdict()
d
Which outputs an ordered dictionary like this:它输出一个这样的有序字典:
OrderedDict([('Id', '1495),('Acct_num', '5001'),('Acct_Name', 'Alpha'),('Prod', 'ret34'), ('Date','2020-04-30'),('Rev',4999)])
Use to_dict
with orient="index"将
to_dict
与 orient="index" 一起使用
'index': dict like {index -> {column -> value}}
'index': 像 {index -> {column -> value}} 这样的字典
d = df.to_dict(orient="index")
d
{1495: {'Acct_num': 5001, 'Acct_Name': 'Alpha', 'Prod': 'ret34', 'Date': '4/30/2020', 'Rev': 4999},
1496: {'Acct_num': 5002, 'Acct_Name': 'Beta', 'Prod': 'pro45', 'Date': '4/30/2020', 'Rev': 18076},
1497: {'Acct_num': 5003, 'Acct_Name': 'Gamma', 'Prod': 'sli55', 'Date': '4/30/2020', 'Rev': 5671},
1498: {'Acct_num': 5004, 'Acct_Name': 'Delta', 'Prod': 'ret34', 'Date': '4/30/2020', 'Rev': 16683}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.