1

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!

M.wol
  • 901
  • 3
  • 10
  • 21

3 Answers3

2

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']]}
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

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']]}
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
  • 1
    https://stackoverflow.com/questions/24870953/does-pandas-iterrows-have-performance-issues/24871316#24871316 – jezrael May 25 '20 at 09:07
0

Here you go:

output = {}
for i, row in df.iterrows():
    output['Points'] = [[row['x'], row['y']]

print(output)
Pratik Joshi
  • 389
  • 4
  • 13