7

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]

2 Answers 2

10

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

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

2 Comments

It is not needed to give an axis for empty dimensions. It finds it automatically. There are also two ways for using it: np.squeeze(your_array) or your_array.squeeze()
True, though I think the question was only wanting to check a specific dimension/axis. I do prefer the array.squeeze(axis=2) syntax though.
5

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]]])

Comments

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.