Reputation: 3266
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.
Upvotes: 3
Views: 6406
Reputation: 214927
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]]]])
Upvotes: 7