pandas 三维熊猫数据帧错误“必须通过二维输入”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50765211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:40:11 来源:igfitidea点击:
Three Dimensional Pandas DataFrame Error "Must Pass 2-D Input"
提问by kel
I am trying to put a 3-D array into a pandas dataframe:
我正在尝试将 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)))
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
回答by piRSquared
- Use
from_product
for your columns - Reshape your array after a transpose
- 使用
from_product
您的列 - 转置后重塑您的阵列
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