2

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 ?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.