2

NumPy arrays may be indexed with other arrays. To illustrate:

>>> import numpy as np

>>> arr = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0et ], 'f4')
>>> ids = np.array([0, 2], 'i4')
arr[ids]
array([ 0.,  2.], dtype=float32)

But what if I wanted to have a multiarray with the value pointed by the index plus the three subsequents elements?

>>> arr[ids:(ids+4)]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
IndexError: invalid slice

Expected:

array([[0. 1. 2. 3.], [2. 3. 4. 5.]], dtype=float32)

How to make this possible?

1
  • I think you either have one two many elements in each of the subarrays of the expected output or othewise you meant arr[ids:(ids+4)], right? Commented Sep 3, 2017 at 16:16

1 Answer 1

3

Use broadcasted addition to create all those indices and then index -

all_idx = ids[:,None]+range(4) # or np.add.outer(ids, range(4))
out = arr[all_idx]

Using np.lib.stride_tricks.as_strided based strided_app -

strided_app(arr, 4, S=1)[ids]
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.