Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Dictionary with numpy arrays

I have a pandas df like the following:

import pandas as pd
import numpy as np
data = np.random.rand(10,2)
data
array([[0.88095214, 0.62363749],
       [0.99251732, 0.97059244],
       [0.00781931, 0.91413354],
       [0.06914494, 0.15208756],
       [0.16956942, 0.5940167 ],
       [0.82641049, 0.91961484],
       [0.75171128, 0.85216832],
       [0.69719183, 0.49129458],
       [0.93801912, 0.94206815],
       [0.0730068 , 0.06453355]])
df = pd.DataFrame(data=data, index=range(10), columns = ["col1","col2"])
df

       col1      col2
0  0.880952  0.623637
1  0.992517  0.970592
2  0.007819  0.914134
3  0.069145  0.152088
4  0.169569  0.594017
5  0.826410  0.919615
6  0.751711  0.852168
7  0.697192  0.491295
8  0.938019  0.942068
9  0.073007  0.064534

Now I want to create an dictionary with the index as key and as a value a numpy array with all values in that line. So:

0 => [0.880952, 0.623637]
...

I know there is a function to_dict('index') from pandas, but this yields a dictionary instead of numpy array as values.

Any ideas? Thank you!

like image 403
Lukas Hestermeyer Avatar asked Mar 16 '26 04:03

Lukas Hestermeyer


1 Answers

If need lists:

You need transpose first and then use parameter orient='list':

d = df.T.to_dict('list')

Or use zip:

d = dict(zip(df.index, df.values.tolist()))

If need numpy arrays:

d = dict(zip(df.index, df.values))
like image 95
jezrael Avatar answered Mar 19 '26 01:03

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!