Ivelin
Ivelin

Reputation: 13329

How to index with array and slice numpy array at the same time

I have a vector with indexes and vector with values.

For every index in the indexes vector I need to efficiently produce a row in numpy array of reslts

The row in the results array needs to contain the previous value of the index in values, the indexed value and two next values.

Here is how I do this with a loop:

import numpy as np

indexes = np.array([5,10,12])
values =  np.array([ 0.89643977,  0.50794841,  0.75995795,  0.78029348,  0.83609961,
        0.47534985,  0.17330516,  0.15152753,  0.15504392,  0.10245308,
        0.70428183,  0.36804107,  0.13074141,  0.77377332,  0.11368238,
        0.74711745,  0.89431082,  0.35544423,  0.08592396,  0.28762   ])

result = values[indexes[0] -1:index[0] -1 + 4]
for index in indexes[1:]:
    result = numpy.vstack([result, values[index -1:index -1 + 4]])

print result
[[ 0.83609961  0.47534985  0.17330516  0.15152753]
 [ 0.10245308  0.70428183  0.36804107  0.13074141]
 [ 0.36804107  0.13074141  0.77377332  0.11368238]]

My indexes and values arrays are big and the loop takes too much time. Is there a way to do this with out a loop?

Upvotes: 1

Views: 922

Answers (2)

Jaime
Jaime

Reputation: 67507

This will work as long as no index falls out of bounds, and should be much faster:

In [4]: idx = indexes[:, None] + np.arange(-1, 3)

In [5]: values[idx]
Out[5]:
array([[ 0.83609961,  0.47534985,  0.17330516,  0.15152753],
       [ 0.10245308,  0.70428183,  0.36804107,  0.13074141],
       [ 0.36804107,  0.13074141,  0.77377332,  0.11368238]])

Upvotes: 2

etna
etna

Reputation: 1083

Is there any reason why you chose values[index -1:][:4] over values[index -1: index -1 + 4]? Also my guess is you rather want to gather all results in a list and then np.vstack rather that doing it in the loop. Pending better answers, you can thus consider using:

ls_results = [values[index -1:index -1 + 4] for index in indexes]
result = np.vstack(ls_results)

Upvotes: 1

Related Questions