7

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.

3
  • You have to set the second parameter of `randint´ to 3 in order to get values of [0, 1, 2]. Commented Jun 24, 2014 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 :-) Commented Jun 24, 2014 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. Commented Jun 24, 2014 at 7:58

2 Answers 2

18
>>> 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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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]])

1 Comment

Works, but using a list comprehension with NumPy kind of defeats the point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.