Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove empty dimension of numpy array

I have a numpy array of shape (X,Y,Z). I want to check each of the Z dimension and delete the non-zero dimension really fast.

Detailed explanation:

I would like to check array[:,:,0] if any entry is non-zero.

If yes, ignore and check array[:,:,1].

Else if No, delete dimension array[:,:,0]

like image 306
a_parida Avatar asked Jan 01 '23 11:01

a_parida


2 Answers

Also not 100% sure what your after but I think you want

np.squeeze(array, axis=2)

https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.squeeze.html

like image 156
J.Warren Avatar answered Feb 02 '23 00:02

J.Warren


I'm not certain what you want but this hopefully points in the right direction.

Edit 1st Jan:
Inspired by @J.Warren's use of np.squeeze I think np.compress may be more appropriate.

This does the compression in one line

np.compress((a!=0).sum(axis=(0,1)), a, axis=2) # 

To explain the first parameter in np.compress

(a!=0).sum(axis=(0, 1)) # sum across both the 0th and 1st axes. 
Out[37]: array([1, 1, 0, 0, 2])  # Keep the slices where the array !=0

My first answer which may no longer be relevant

import numpy as np

a=np.random.randint(2, size=(3,4,5))*np.random.randint(2, size=(3,4,5))*np.random.randint(2, size=(3,4,5))
# Make a an array of mainly zeroes.
a
Out[31]:
array([[[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]],

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

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

res=np.zeros(a.shape[2], dtype=np.bool)
for ix in range(a.shape[2]):
    res[ix] = (a[...,ix]!=0).any()

res
Out[34]: array([ True,  True, False, False,  True], dtype=bool)
# res is a boolean array of which slices of 'a' contain nonzero data

a[...,res]
# use this array to index a
# The output contains the nonzero slices
Out[35]:
array([[[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0]],

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

       [[0, 0, 0],
        [0, 0, 1],
        [0, 0, 0],
        [1, 0, 0]]])
like image 29
Tls Chris Avatar answered Feb 02 '23 00:02

Tls Chris