Python 将六维数组重塑为二维数据帧
我有一个六维的数字数组,我想把它重塑成一个二维数组。结果矩阵的行应按A的前三个维度进行多索引,列应按A的后三个维度进行多索引。使用pandas或numpy实现这一点的最佳方法是什么?这里有一个方便的函数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(
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)