Reputation: 180
I want to use an api and would need to put my dataframe in a dictionary format first. The dataframe df that looks like this:
OrigC OrigZ OrigN Weigh DestC DestZ DestN
0 PL 97 TP 59 DE 63 SN
Exepected output of the first row:
{"section":[
{"location":
{
"zipCode":
{"OrigC": "PL",
"OrigZ":"97"},
"location": {"id": "1"},
"OrigN": "TP"
},
"carriageParameter":
{"road":
{"truckLoad": "Auto"}
},
"load":
{"Weigh": "59",
"unit": "ton",
"showEmissionsAtResponse": "true"
}
},
{"location":
{
"zipCode":
{"DestC": "DE",
"DestZ":"63"},
"location": {"id": "2"},
"DestN": "SN"
},
"carriageParameter":
{"road":
{"truckLoad":"Auto"}
},
"unload":
{"WEIGHTTONS":"59",
"unit": "ton",
"showEmissionsAtResponse": "true"
}
}]}
Note that there is static information in the dictionary that doesn't require any change.
How can this be done in Python?
Upvotes: 1
Views: 47
Reputation: 9481
You can use iterrows.
dic = {}
dic['section'] = []
for ix, row in df.iterrows():
in_dict = {
'location': {
'zip_code': {
'OrigC': row['OrigC'],
'OrigZ': row['OrigZ'],
},
'location': {'id': ix+1}, # I am guessing here.
'OrigN': 'TP',
},
'CarriageParameter': {
'road': {
'truckLoad': 'Auto'}
},
'load': {
'Weigh': str(row['Weigh']),
}
}
dic['section'].append(in_dict)
Note that this is not the entire entry, but I think it is clear enough to illustrate the idea.
Upvotes: 3