I recently started working with python and I am now working with API request. I need to convert dataframe to a dictionary of lists nested in the list.
How to convert df
:
data = {'x': ['15.0', '42.2','43.4','89.0','45.8'],
'y': ['10.1', '42.3','43.5','5.0','45.9']
}
df = pd.DataFrame (data, columns = ['x','y'])
To dictionary of lists nested in the list
{
"Points": [
[15.0, 10.1], [42.2, 42.3], [43.4, 43.5], [89.0, 5.0], [45.8, 45.9]
]
}
I tried using df.to_dict
with list as a orient parameter but the result is 2 long lists of x and y instead of many pair-lists.
Probably trivial problem for python users, thanks for help in advance!
Convert values to numpy array by DataFrame.to_numpy
and then to list:
d = {"Points":df.to_numpy().tolist()}
#if there is more columns
#d = {"Points":df[['x','y']].to_numpy().tolist()}
print (d)
{'Points': [['15.0', '10.1'], ['42.2', '42.3'],
['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
You can do this:-
res = {'Points' : [[row['x'], row['y']] for i, row in df.iterrows()]}
print(res)
Output:-
{'Points': [['15.0', '10.1'], ['42.2', '42.3'], ['43.4', '43.5'], ['89.0', '5.0'], ['45.8', '45.9']]}
Here you go:
output = {}
for i, row in df.iterrows():
output['Points'] = [[row['x'], row['y']]
print(output)
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.