Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将六维数组重塑为二维数据帧_Python_Pandas_Numpy - Fatal编程技术网

Python 将六维数组重塑为二维数据帧

Python 将六维数组重塑为二维数据帧,python,pandas,numpy,Python,Pandas,Numpy,我有一个六维的数字数组,我想把它重塑成一个二维数组。结果矩阵的行应按A的前三个维度进行多索引,列应按A的后三个维度进行多索引。使用pandas或numpy实现这一点的最佳方法是什么?这里有一个方便的函数 def make2d(a): shape = a.shape n = len(shape) col_lvls = n // 2 idx_lvls = n - col_lvls midx = pd.MultiIndex.from_product(

我有一个六维的数字数组,我想把它重塑成一个二维数组。结果矩阵的行应按A的前三个维度进行多索引,列应按A的后三个维度进行多索引。使用pandas或numpy实现这一点的最佳方法是什么?

这里有一个方便的函数

def make2d(a):
    shape = a.shape
    n = len(shape)
    col_lvls = n // 2
    idx_lvls = n - col_lvls

    midx = pd.MultiIndex.from_product(
        [range(i) for i in shape[:idx_lvls]],
        names=['d-{}'.format(d) for d in range(1, idx_lvls + 1)])
    mcol = pd.MultiIndex.from_product(
        [range(i) for i in shape[idx_lvls:]],
        names=['d-{}'.format(d) for d in range(idx_lvls + 1, idx_lvls + col_lvls + 1)])

    return pd.DataFrame(
        a.reshape(np.array(shape[:3]).prod(), -1),
        midx, mcol
    )

演示

a = np.arange(216).reshape(2, 3, 2, 3, 2, 3)

make2d(a)