基于索引的numpy重塑

Gus*_*pes 5 python numpy reshape

我有一个数组:

arr = [
  ['00', '01', '02'],
  ['10', '11', '12'],
]
Run Code Online (Sandbox Code Playgroud)

我想考虑其索引重塑此数组:

reshaped = [
  [0, 0, '00'],
  [0, 1, '01'],
  [0, 2, '02'],
  [1, 0, '10'],
  [1, 1, '11'],
  [1, 2, '12'],
]
Run Code Online (Sandbox Code Playgroud)

是否有一个numpypandas办法做到这一点?还是我必须做好旧事for

for x, arr_x in enumerate(arr):
    for y, val in enumerate(arr_x):
        print(x, y, val)
Run Code Online (Sandbox Code Playgroud)

Ger*_*ges 7

您可以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)
Run Code Online (Sandbox Code Playgroud)