1

How can I create a dataframe from a dictionary of 2D arrays such that each element in the dataframe is an array? For example, I would like df.iloc[0]["A"] below to return a [0,0,0]

import pandas as pd
import numpy as np

data = {"A":np.zeros([100,3]), "B":np.zeros([100,3]), "C":np.zeros([100,3])}
df = pd.DataFrame.from_dict(data)
# print(df.iloc[0]["A"]) = [0,0,0]

2 Answers 2

2

I would use MultiIndex:

df = pd.DataFrame({k:x.ravel() for k,x in data.items()},
                  index=pd.MultiIndex.from_product([np.arange(100), np.arange(3)]))

Then df.loc[0,'A'] gives you a series:

0    0.0
1    0.0
2    0.0
Name: A, dtype: float64
Sign up to request clarification or add additional context in comments.

Comments

1

If you're willing to accept them being Python lists instead of np.arrays, you can do this:

data = {"A": np.zeros([100,3]).tolist()}
df = pd.DataFrame.from_dict(data)

print(df.iloc[0]["A"])
[0.0, 0.0, 0.0]

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.