2
votes

I have an array A of size [1, x] of values and an array B of size [1, y] (y > x) of indexes corresponding to array A. I want as result an array C of size [1,y] filled with values of A.

Here is an example of inputs and outputs:

>>> A = [6, 7, 8]
>>> B = [0, 2, 0, 0, 1]
>>> C = #Some operations
>>> C
[6, 8, 6, 6, 7]

Of course I could solve it like that:

>>> C = []
>>> for val in B:
>>>     C.append(A[val])

But I was actually expected a nicer way to do it. Especially because I want to use it as an argument of another function. An expression looking like A[B] (but a working one) would be ideal. I don't mind solution using NumPy or pandas.

6

6 Answers

2
votes

Simple with a list comprehension:

A = [6, 7, 8]
B = [0, 2, 0, 0, 1]

C = [A[i] for i in B]
print(C)

This yields

[6, 8, 6, 6, 7]
2
votes

For fetching multiple items operator.itemgetter comes in handy:

from operator import itemgetter
A = [6, 7, 8]
B = [0, 2, 0, 0, 1]

itemgetter(*B)(A)
# (6, 8, 6, 6, 7)

Also as you've mentioned numpy, this could be done directly by indexing the array as you've specified, i.e. A[B]:

import numpy as np
A = np.array([6, 7, 8])
B = np.array([0, 2, 0, 0, 1])

A[B]
# array([6, 8, 6, 6, 7])

Another option is to use np.take:

np.take(A,B)
# array([6, 8, 6, 6, 7])
1
votes

This is one way, using numpy ndarrays:

import numpy as np

A = [6, 7, 8]
B = [0, 2, 0, 0, 1]
C = list(np.array(A)[B]) # No need to convert B into an ndarray
                         # list() is for converting ndarray back into a list,
                         # (if that's what you finally want)
print (C)

Explanation

  1. Given a numpy ndarray (np.array(A)), we can index into it using an array of integers (which happens to be exactly what your preferred form of solution is): The array of integers that you use for indexing into the ndarray, need not be another ndarray. It can even be a list, and that suits us too, since B happens to a list. So, what we have is:

    np.array(A)[B]
    
  2. The result of such an indexing would be another ndarray, having the same shape (dimensions) as the array of indexes. So, in our case, as we are indexing into an ndarray using a list of integer indexes, the result of that indexing would be a one-dimensional ndarray of the same length as the list of indexes.

  3. Finally, if we want to convert the above result, from a one-dimensional ndarray back into a list, we can pass it as an argument to list():

    list(np.array(A)[B])
    
0
votes

You could do it with list comprehension:

>>> A = [6, 7, 8]
>>> B = [0, 2, 0, 0, 1]
>>> C = [A[x] for x in B]
>>> print(C)
[6, 8, 6, 6, 7]
0
votes

I think you need a generator (list comprehension):

A = [1, 2, 3]
B = [0, 2, 0, 0, 1]
C = [A[i] for i in B]
0
votes

Once you're using numpy.array you're able to do exactly what you want with syntax you expect:

>>> a = array([6, 7, 8])
>>> b = array([0, 2, 0, 0, 1])
>>> a[b]
array([6, 8, 6, 6, 7])