2

In numpy I have a 3d array and I would ike to remove some of the 2d subarrays. Think about it like this:

r = range(27)
arr = np.reshape(r, (3,3,3))

del = [[0,1,2],[0,0,2]]
flatSeam = np.ravel_multi_index(del, arr.shape)
arr = np.delete(arr, flatSeam)

So at the end I would like to have an array of the shape (3,2,3) without the elements 00, 10, 22 from the original array. My problem is that I acn not use ravel_multi_index for this, because my indices are 2d and the array shape is 3d, so the wrong indices are calculated (the code above also does not execute because the indices array and the shape have to be the same size).

Do you have any ideas how I can achieve this?

3
  • So, the first row of del would always be range(arr.shape[1]), like you have [0,1,2], here ? Commented Nov 15, 2016 at 13:51
  • The first row of del should be range(arr.shape[0]). So first row are the row indices and the second row are the column indices. Commented Nov 15, 2016 at 13:55
  • Ah that makes sense. Commented Nov 15, 2016 at 13:58

1 Answer 1

3

Here's an approach using advanced-indexing -

# arr: Input array, rm_idx : 2-row list/array of indices to be removed
m,n,p = arr.shape
mask = np.asarray(rm_idx[1])[:,None] != np.arange(n)
out = arr[np.arange(m)[:,None],np.where(mask)[1].reshape(m,-1)]

Alternatively, with boolean-indexing -

out = arr.reshape(-1,p)[mask.ravel()].reshape(m,-1,p)

A bit less memory-intensive approach as we try to avoid creating 2D mask -

vmask = ~np.in1d(np.arange(m*n),rm_idx[1] + n*np.arange(m))
out = arr.reshape(-1,p)[vmask].reshape(m,-1,p)
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for this! From which namespaces comes rm_idx? Oh sorry this is my del array right?
@Cilenco rm_idx would be your del. I used a different variable name as there's del operator in Python, so that might cause conflict.
Ah okay good point! But with this I get following error: TypeError: list indices must be integers or slices, not tuple in the mask line
@Cilenco I was assuming it to be an array. Edited to accept both arrays and list.
Ah yes okay. Works great now :) Thanks for your help!
|

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.