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.
The for loop isn't a problem, neither is the upload to the internal system. I cannot seem to get the format of the dictionary correct for the upload to proceed.
Here is a model of the dataframe:
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
I need each row of the dataframe to look like the below (first two rows):
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"
'index': dict like {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}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.