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?

Divakar
  • 218,885
  • 19
  • 262
  • 358
Mano-Wii
  • 592
  • 5
  • 19
  • 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? – jdehesa Sep 03 '17 at 16:16

1 Answers1

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]
Divakar
  • 218,885
  • 19
  • 262
  • 358