-1

Similar question which shows how to do column or row: remove zero lines 2-D numpy array

I'm looking for a one liner that can remove rows and columns from an array that only have False or 0. I can currently do this in two lines as follows and my attempt at doing it in one line will be shown.

Consider array:

arr = array([[[False, False, False, False, False, False, False],
              [False, False, False, False, False, False, False],
              [False, False,  True,  True,  True, False, False],
              [False, False,  True,  True,  True, False, False],
              [False, False,  True,  True,  True, False, False],
              [False, False, False, False, False, False, False],
              [False, False, False, False, False, False, False]]])

Remove rows

arr_2 = arr[~np.all(arr == False, axis=1), :]
arr_2
array([[False, False,  True,  True,  True, False, False],
       [False, False,  True,  True,  True, False, False],
       [False, False,  True,  True,  True, False, False]])

Remove columns

arr_3 = arr_2[:, ~np.all(arr_2 == False, axis=0)]
arr_3
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

This achieves the desired outcome. I think this should be doable in one line.

My attempt at one line

arr_4 = arr[~np.all(arr == False, axis=1), ~np.all(arr == False, axis=0)]
arr_4 = array([ True,  True,  True])

Obviously this is not the desired result

akozi
  • 425
  • 1
  • 7
  • 20

1 Answers1

2

Create open indexing arrays with np.ix_ and then index into input array -

arr[np.ix_(np.any(arr, axis=1),np.any(arr, axis=0))]
Divakar
  • 218,885
  • 19
  • 262
  • 358