Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove 2d slice from 3d numpy array

I need to remove the last arrays from a 3D numpy cube. I have:

a = np.array(
[[[1,2,3],
 [4,5,6],
 [7,8,9]],

[[9,8,7],
 [6,5,4],
 [3,2,1]],

[[0,0,0],
 [0,0,0],
 [0,0,0]],

[[0,0,0],
 [0,0,0],
 [0,0,0]]])

How do I remove the arrays with zero sub-arrays like at the bottom side of the cube, using np.delete?

(I cannot simply remove all zero values, because there will be zeros in the data on the top side)

like image 516
Claire.gen Avatar asked Oct 07 '19 18:10

Claire.gen


2 Answers

For a 3D cube, you might check all against the last two axes

a = np.asarray(a)
a[~(a==0).all((2,1))]

array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])
like image 115
rafaelc Avatar answered Nov 14 '22 22:11

rafaelc


Here's one way to remove trailing all zeros slices, as mentioned in the question that we want to keep the all zeros slices in the data on the top side -

a[:-(a==0).all((1,2))[::-1].argmin()]

Sample run -

In [80]: a
Out[80]: 
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])

In [81]: a[:-(a==0).all((1,2))[::-1].argmin()]
Out[81]: 
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]]])
like image 32
Divakar Avatar answered Nov 14 '22 23:11

Divakar