Reputation: 123
I am trying to put a 3-D array into a pandas dataframe:
import pandas as pd
import numpy as np
A = np.arange(1, 9).reshape(2, 2, 2)
lable_one = np.array(['one', 'two'])
lable_two = np.array(['a', 'b'])
df = pd.DataFrame(
A,columns=pd.MultiIndex.from_tuples((lable_one,lable_two)))
columns=pd.MultiIndex.from_tuples((lable_one, lable_two)))
Error:
ValueError: Must pass 2-d input
My desired output is:
one two
a b a b
0 1 5 2 7
1 3 6 4 8
Upvotes: 6
Views: 93631
Reputation: 294218
from_product
for your columnslable_one = np.array(['one', 'two'])
lable_two = np.array(['a', 'b'])
cols = pd.MultiIndex.from_product([lable_one, lable_two])
pd.DataFrame(A.T.reshape(2, -1), columns=cols)
one two
a b a b
0 1 5 3 7
1 2 6 4 8
Upvotes: 7