0

Is there a function or more concise notation to get b or bb in the code snippet below?

import numpy as np

a = np.arange(12).reshape(3, 4)
c = (1, 2)
r = 1
b = a[c[0]-r:c[0]+r, c[1]-r:c[1]+r]
bb = a[c[0]-r:c[0]+r+1, c[1]-r:c[1]+r+1]

The objective is to get a subarray defined by a center index c and radius r (L1-norm).

4
  • What's wrong with your current approach? Commented Oct 11, 2022 at 20:00
  • What exactly is wrong with bb?. It seems like a pythonic solution and how numpy is intended to work. Commented Oct 11, 2022 at 20:02
  • @mozway @Timo Imagine a higher dimensional array, e.g. 8, and all the cruft hiding intended meaning, which is c-r:c+r. Commented Oct 11, 2022 at 20:05
  • 1
    Not much better in my opinion, but you might consider a[tuple(slice(i-r, i+r) for i in c)] for higher dimensions. Commented Oct 11, 2022 at 20:10

0

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.