How To Efficiently Select Multiple Slices From An Array?
Given an array d = np.random.randn(100) and an index array i = np.random.random_integers(low=3, high=d.size - 5, size=20) how can I efficiently create a 2d array r with r.shape =
Solution 1:
You can create a windowed view of your data, i.e. a (93, 8)
array, where item [i, j]
is item [i+j]
of your original array, as:
>>>from numpy.lib.stride_tricks import as_strided>>>wd = as_strided(d, shape=(len(d)-8+1, 8), strides=d.strides*2)
You can now extract your desired slices as:
>>>r = wd[i-3]
Note that wd
is simply a view of your original data, so it takes no extra memory. The moment you extract r
with arbitrary indices, the data is copied. So depending on how you want to use your r
array, you may want to delay that as much as possible, or maybe even avoid it altogether: you can always access what would be row r[j]
as wd[j-3]
without triggering a copy.
Post a Comment for "How To Efficiently Select Multiple Slices From An Array?"