3

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]]])
7
  • You probably need to create a new, smaller array, and then copy what you need. There is no way to delete what you need in a loop because the array is not fixed-sized. Commented Dec 20, 2018 at 17:16
  • 1
    So, the code I posted is the only way to do achieve this? Ah, rip, I was hoping numpy had some way to do this which was more optimized. Commented Dec 20, 2018 at 17:17
  • The code you posted delete the rows of a[i]'s, not the columns. Which exactly do you want to delete, rows or columns? Commented Dec 20, 2018 at 17:20
  • @QuangHoang, the array is 3d, so the names 'rows' and 'columns' are ambiguous. Here the OP is thinking of the 0 and 1 axes, you seem think of them as 1 and 2. Commented Dec 20, 2018 at 17:23
  • @MatthieuBrucher, np.delete makes a new array too. Commented Dec 20, 2018 at 17:24

1 Answer 1

4

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]]]
Sign up to request clarification or add additional context in comments.

2 Comments

There's nothing hacky about that. np.delete does that sort of boolean masking, but doesn't generalize it to the 2d case as you did. I was slowly working toward this sort of solution. The last reshape can be reshape(a0, -1, a2).
@hpaulj Thanks for your comments, updated the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.