1

Suppose I have a numpy array A which can be of any dimensions len(A.shape) can be 1,2,3,..etc. and a corresponding array, crop which len(crop) = len(A.shape) and I want to extract the interior values of A using crop. Here is an example for 2D array.

    A = np.random.rand(30).reshape([5,6])
    crop = np.array([1,2])

Wanted output:

    A[crop[0]:-crop[0], crop[1]:-crop[1])

Assuming value of crop will be reasonable with respect to size of A. How do I do this for any dimension of array A ?

Ong Beng Seong
  • 196
  • 1
  • 11

1 Answers1

3

Here's one way with slice notation -

A[tuple([slice(i,-i,None) for i in crop])]

Or with the shorthand np.s_ -

A[tuple([np.s_[i:-i] for i in crop])]

If the start and end indices are given for each dimension, we can do something like as shown in Slicing NumPy array given start and end indices for generic dimensions.

Divakar
  • 218,885
  • 19
  • 262
  • 358