三维Pandas DataFrame错误“必须通过2-D输入”

时间:2018-06-08 16:49:20

标签: python pandas dataframe 3d

我正在尝试将3-D数组放入pandas数据帧:

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)))

错误:

ValueError: Must pass 2-d input

我想要的输出是:

   one    two
   a  b   a  b
0  1  5   2  7 
1  3  6   4  8

1 个答案:

答案 0 :(得分:0)

  1. 使用from_product作为列
  2. 转置后重塑阵列
  3. 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