kel
kel

Reputation: 123

Three Dimensional Pandas DataFrame Error "Must Pass 2-D Input"

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

Answers (1)

piRSquared
piRSquared

Reputation: 294218

  1. Use from_product for your columns
  2. Reshape your array after a transpose

lable_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

Related Questions