2

I have a question regarding the deletion from arrays. I have a 3-D numpy array (coordinates are z,y,x) with an estimated 900^3 size. Only a few values are nonzero, but they have a nontrivial spatial distribution. I want to delete all 2-D slices in that array which have only zeros in it. In other words, I want an array with minimum size which still has all relevant data in it.

My attempt looks like:

    while np.all(a[0]==0):
        a=np.delete(a,0,0)
    while np.all(a[a.shape[0]-1]==0) and a.shape[0]>1:
        a=np.delete(a,-1,0)

and seems to work for the z-direction. How can I do something equal in the other two directions? And is there maybe another way of doing it better?

Another Idea was

tmp=np.delete(tmp,np.all(tmp==0,axis=1),1)

but that one seems to work only from the start and leaves out the zeros at the end.

Is it maybe possible, to rotate an array in 3D space?

1
  • If you want to rotate the array in 3d space, you can use numpy.roll. Commented Dec 1, 2012 at 1:18

2 Answers 2

0

You can use transpose to rearrange your axes, but it sounds like you might really be looking for a sparse array

3
  • I'm not sure, what you mean by this. Sparse arrays are 2D or not? Commented Nov 30, 2012 at 12:08
  • In scipy, yes...good point. I'll leave it in my answer just in case it might help someone with a 2D problem. People have implemented multidimensional sparse arrays, which might be good depending on what exactly you need to do with the points afterward, if you check this out for example: janeriksolem.net/2010/02/…. But if your code works for the z-direction, why not just transpose to rotate the dimensions twice to repeat the process, then once more to get back to the original order? Commented Nov 30, 2012 at 12:13
  • Actually yes, that works. Might still look like magic to me, but actually it does the job. Thanks. Commented Nov 30, 2012 at 12:15
0

This is a fun problem, here is what I came up with:

for ax in range(3):
    all_but_ax = [i for i in range(3) if i != ax]
    a = delete(a, where(apply_over_axes(sum, abs(a), all_but_ax).ravel() == 0), 
                  ax)

So you some the abs(a) over all but the current axis == current 2D slice, and check if it is zero, which means it is empty. The where gives the indices for the delete.

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.