Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a mx1 array, a, that contains some values. Moreover, I have a nxk array, say b, that contains indices between 0 and m.

Example:

a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))

For every index value in b I want to get the corresponding value from a. I can do it with a loop:

c = np.zeros_like(b).astype('float')
n, k = b.shape
for i in range(n):
    for j in range(k):
        c[i, j] = a[b[i, j]]

Is there any built-it numpy function or trick that is more elegant? This approach looks a little dumb to me. PS: originally, a and b are Pandas objects if that helps.

share|improve this question
    
You have to set the second parameter of `randint´ to 3 in order to get values of [0, 1, 2]. –  MaxPowers Jun 24 at 7:44
    
Thanks, I sometimes struggle with the half-open intervals notation. Coming from Matlab/R/Gauss, every now and then I fall back :-) –  BayerSe Jun 24 at 7:57
    
It doesn't help that the standard library random module includes the right endpoint for random.randint, while NumPy excludes it for numpy.random.randint. –  user2357112 Jun 24 at 7:58
add comment

2 Answers

up vote 7 down vote accepted
>>> a
array([ 0.1,  0.2,  0.3])
>>> b
array([[0, 0, 1, 1],
       [0, 0, 1, 1],
       [0, 1, 1, 0],
       [0, 1, 0, 1]])
>>> a[b]
array([[ 0.1,  0.1,  0.2,  0.2],
       [ 0.1,  0.1,  0.2,  0.2],
       [ 0.1,  0.2,  0.2,  0.1],
       [ 0.1,  0.2,  0.1,  0.2]])

Tada! It's just a[b]. (Also, you probably wanted the upper bound on the randint call to be 3.)

share|improve this answer
add comment

Try iteration with a numpy.flatiter object:

a = np.array((0.1, 0.2, 0.3))
b = np.random.randint(0, 3, (4, 4))

c = np.array([a[i] for i in b.flat]).reshape(b.shape)
print(c)

array([[ 0.2,  0.2,  0.2,  0.1],
       [ 0.3,  0.3,  0.2,  0.1],
       [ 0.2,  0.1,  0.3,  0.3],
       [ 0.3,  0.3,  0.3,  0.1]])
share|improve this answer
1  
Works, but using a list comprehension with NumPy kind of defeats the point. –  user2357112 Jun 24 at 7:50
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.