2

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!

1 Answer 1

8

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.