3

I want to replace the values in a given numpy array (A) at a given index (e.g. 0), along a given axis (e.g. -2) with a given value (e.g. 0), equivalently:

A[:,:,0,:]=0

Problem is the input array A may come in as 3D or 4D or other shapes, so for 3D data I would need

A[:,0,:]=0

If it's 5D: A[:,:,:,0,:]=0

Currently I'm using an exec() to get this done:

slicestr=[':']*numpy.ndim(var)
slicestr[-2]=str(0)
slicestr=','.join(slicestr)
cmd='A[%s]=0' %slicestr
exec(cmd)
return A

I'm a bit concerned that the usage of exec() might not be quite a nice approach. I know that numpy.take() can give me the column at specific index along specific axis, but to replace values I still need to construct the slicing/indexing string, which is dynamic. So I wonder is there any native numpy way of achieving this?

Thanks.

1 Answer 1

7

You can use Ellipsis (see numpy indexing for more) to skip the first few dimensions:

# assert A.ndim >= 2
A[...,0,:]=0

A2d = np.arange(12).reshape(2,6)
A3d = np.arange(12).reshape(2,3,2)
A4d = np.arange(12).reshape(2,1,3,2)

A2d[...,0,:] = 0

A2d
#array([[ 0,  0,  0,  0,  0,  0],
#       [ 6,  7,  8,  9, 10, 11]])

A3d[...,0,:] = 0

A3d
#array([[[ 0,  0],
#        [ 2,  3],
#        [ 4,  5]],

#       [[ 0,  0],
#        [ 8,  9],
#        [10, 11]]])

A4d[...,0,:] = 0

A4d
#array([[[[ 0,  0],
#         [ 2,  3],
#         [ 4,  5]]],  

#       [[[ 0,  0],
#         [ 8,  9],
#         [10, 11]]]])
Sign up to request clarification or add additional context in comments.

6 Comments

Note to readers: Ellipsis works on python3.x only. For 2.x, you'd need to build a slice object.
Cool, that's I'm looking for! And it has nothing to do with python3 or 2, it is a numpy thing.
@cᴏʟᴅsᴘᴇᴇᴅ Which python 2.x are you using? It seems working for me on python 2.7.13 and numpy 1.12.0.
The Ellipsis object exists on 2.x as well, but the ... syntax is invalid, at least on the version I'm using (2.7.10).
tested and worked in a conda env with python=2.7.10 and numpy=1.12.0, also worked in python=2.6.9 with numpy=1.9.2
|

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.