Numpy: Find The Values Of Rows Given An Array Of Indexes
I have a 2D array of values and a 1D array of indexes. I want to pull the values from the index of each row using an array of indexes. The following code would do this successfully
Solution 1:
This should do it:
row = numpy.arange(_2Darray.shape[0])
index_values = _2Darray[row, array_indexes]
Numpy allows you to index 2d arrays (or nd arrays really) with two arrays such that:
for i inrange(len(row)):
result1[i] =array[row[i], col[i]]
result2 =array[row, col]
numpy.all(result1 == result2)
Solution 2:
In [15]: _2Darray[np.arange(len(_2Darray)), [5,5,5,4,4,4,6,6,6,8]]
Out[15]: array([ 5., 15., 25., 34., 44., 54., 66., 76., 86., 98.],
dtype=float16)
BUT, I think something based on you solution may actually be the faster on smaller arrays. If the arrays are bigger than 100*100
use numpy
indexing.
In [22]: def f(array, indices):
...: return [array[row, index] forrow, index in enumerate(indices)]
In [23]: f(_2Darray, [5,5,5,4,4,4,6,6,6,8])
Out[23]: [5.0, 15.0, 25.0, 34.0, 44.0, 54.0, 66.0, 76.0, 86.0, 98.0]
In [27]: %timeit f(_2Darray,[5,5,5,4,4,4,6,6,6,8])
100000 loops, best of 3: 7.48 us per loop
In [28]: %timeit _2Darray[np.arange(len(_2Darray)), [5,5,5,4,4,4,6,6,6,8]]
10000 loops, best of 3: 24.2 us per loop
Solution 3:
You have to pay attention to use specifically numpy functions designed for arrays, not for matrixes. The two are easy to confuse and do not raise error when methods of one are called on the other, yet the output is pretty much unpredicatable.
Post a Comment for "Numpy: Find The Values Of Rows Given An Array Of Indexes"