Deleting numpy array elements from a 3d numpy array with given array of indices

六眼飞鱼酱① 提交于 2021-02-05 05:51:10

问题


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 ith 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!