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.