简体   繁体   中英

Numpy Remove Rows and Columns from 3d Array

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM