1

Lets say you have a 5x5x5 numpy array

    a = np.ones((5,5,5))
    a[:,3,:] = 0
    a[:,:,3] = 0

(I know it is ugly)

This returns

    [[[1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [0. 0. 0. 0. 0.]
  [1. 1. 1. 0. 1.]]

 [[1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [0. 0. 0. 0. 0.]
  [1. 1. 1. 0. 1.]]

 [[1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [0. 0. 0. 0. 0.]
  [1. 1. 1. 0. 1.]]

 [[1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [0. 0. 0. 0. 0.]
  [1. 1. 1. 0. 1.]]

 [[1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [1. 1. 1. 0. 1.]
  [0. 0. 0. 0. 0.]
  [1. 1. 1. 0. 1.]]]

What i want to do is to remove all rows and columns on all axis that is only 0 returning a new 4x4x4 array with only 1s in it.

I can do this for a 2 dimensional array with

a = np.delete(a,np.where(~a.any(axis=0))[0], axis=1)
a = a[~np.all(a == 0, axis=1)]

But can't figure how to do it with 3 dimensions

Anyone have an idea how that can be done?

3
  • 1
    It's better to use this syntax: a[3, 1, 3] = 0 Commented Jan 6, 2019 at 19:02
  • 1
    You can set all the 0's with: a[:,3,:] = 0 and a[:,:,3]=0 Commented Jan 6, 2019 at 19:12
  • 1
    The new shape would be (5,4,4) for your example. Commented Jan 6, 2019 at 19:12

1 Answer 1

1

You can find the indices of rows with all zero items separately for second and third axes and then remove them using np.delete:

In [25]: mask = (a == 0)

In [26]: sec = np.where(mask.all(1))[1]

In [27]: third = np.where(mask.all(2))[1]

In [28]: new = np.delete(np.delete(a, sec[1], 1), third, 2)

Note that instead of creating a new array you can reassign the result to a if you intended to do so.

Sign up to request clarification or add additional context in comments.

1 Comment

If out comment the a[:,:,3] = 0 from my code then your code errors "index 1 is out of bounds for axis 0 with size 0"

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.