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

时间:2017-02-05 21:06:26

标签: python pandas numpy

我有一个六维数字数组A,我想将它重塑为二维数组。结果矩阵的行应该由A的前三个维度进行多索引,并且列应该由A的最后三个维度进行多索引。使用pandas或numpy实现此目的的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这是一个方便的功能。

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)

enter image description here