我有一个numpy数组:
arr = array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
和一组索引,ind = array([0, 1, 1])
我想对i
中第arr
行进行操作,仅使用numpy.delete删除ind[i]
中第arr[i]
行。
因此从本质上讲,这是一种更Python化的方式:
x, y, z = arr.shape
new_arr = np.empty((x, y - 1, z))
for i, j in enumerate(ind):
new_arr[i] = np.delete(arr[i], j, 0)
arr = new_arr.astype(int)
所以这里的输出将是:
array([[[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[15, 16, 17]],
[[18, 19, 20],
[24, 25, 26]]])
答案 0 :(得分:3)
可行的解决方案:
import numpy as np
arr = np.array([[[0, 1, 2],
[3, 4, 5],
[6, 7, 8]],
[[9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
a0, a1, a2 = arr.shape
indices = np.array([0, 1, 1])
mask = np.ones_like(arr, dtype=bool)
mask[np.arange(a0), indices, :] = False
result = arr[mask].reshape((a0, -1, a2))
print(result)
输出
[[[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[15 16 17]]
[[18 19 20]
[24 25 26]]]