Reputation: 2412
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]
Upvotes: 1
Views: 1046
Reputation: 1012
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]
Upvotes: 1
Reputation: 150745
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
Upvotes: 2