问题
I have a numpy array:
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]]])
and an array of indices, ind = array([0, 1, 1])
What I would like to do is for the i
th row in arr
, delete the ind[i]
th row in arr[i]
using only numpy.delete.
So in essence a more pythonic way to do this:
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)
So the output here would be:
array([[[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[15, 16, 17]],
[[18, 19, 20],
[24, 25, 26]]])
回答1:
A working solution:
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)
Output
[[[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[15 16 17]]
[[18 19 20]
[24 25 26]]]
来源:https://stackoverflow.com/questions/53873232/deleting-numpy-array-elements-from-a-3d-numpy-array-with-given-array-of-indices