I'm wondering if there is a better of writing array cropping/slicing from the end, but in a programmatic way. This means, that the crop size can actually be 0, and I have multiple dimension e.g. a 5D Tensor.
Here a simple example in 2D:
# This is just to have some dummy data
import numpy as np
A = np.random.rand( 10,5)
# The easy standard case:
ix = 1
iy = 1
B = A [ ix:-ix , iy:-iy] # This works
# Now the trickier case, where I'm looking for a pythonic way of doing it.
iy = 0
# Using the code from above, does not what I want => 2nd dim ==0
C1 = A [ ix:-ix , iy:-iy]
# The next line gives the result that I want but hard coded
C2 = A [ ix:-ix , : ]
# The next line also gives me what I want, but gets completely unreadable
# for real variable names and multiple dimensions
C3 = A [ ix:A.shape[0]-ix : iy:A.shape[1]-iy]
# Is there something like this in numpy, similar to Matlab?
C4 = A [ ix:end-ix , iy:end-iy ]
C5 = A [ ix:np.end-ix , iy : np.end-iy ]
I know it doesn't look so bad for 2D but if you have multiple dimensions and real variable names, the code easily messes up. So is there something like "end" from Matlab here in python, or some other more pythonic way?
x[idx]. A number of the numpy functions construct a such a tuple from lists or even arrays. Look also at thenp.lib.indextricks.pyto see the clever tricks behind objects likenp.r_andnp.ogrid.