首页 > 解决方案 > 基于索引的numpy重塑

问题描述

我有一个数组:

arr = [
  ['00', '01', '02'],
  ['10', '11', '12'],
]

考虑到它的索引,我想重塑这个数组:

reshaped = [
  [0, 0, '00'],
  [0, 1, '01'],
  [0, 2, '02'],
  [1, 0, '10'],
  [1, 1, '11'],
  [1, 2, '12'],
]

有没有numpy办法pandas做到这一点?还是我必须做好旧事for

for x, arr_x in enumerate(arr):
    for y, val in enumerate(arr_x):
        print(x, y, val)

标签: pythonnumpyreshape

解决方案


您可以使用np.indices获取索引,然后将所有内容拼接在一起......

arr = np.array(arr)
i, j = np.indices(arr.shape)
np.concatenate([i.reshape(-1, 1), j.reshape(-1, 1), arr.reshape(-1, 1)], axis=1)

推荐阅读