fact
fact

Reputation: 557

Substitute entries of numpy array with numpy arrays

I have a numpy array A of size ((s1,...sm)) with integer entries and a dictionary D with integers as keys and numpy arrays of size ((t)) as values. I would like to evaluate the dictionary on every entry of the array A to get a new array B of size ((s1,...sm,t)).

For example

D={1:[0,1],2:[1,0]}
A=np.array([1,2,1])

The output shout be

array([[0,1],[1,0],[0,1]])

Motivation: I have an array with indexes of unit vectors as entries and I need to transform it into an array with the vectors as entries.

Upvotes: 1

Views: 159

Answers (3)

val
val

Reputation: 8689

If you can rename your keys to be 0-indexed, you might use direct array querying on your unit vectors:

>>> units = np.array([D[1], D[2]])
>>> B = units[A - 1]    # -1 because 0 indexed: 1 -> 0, 2 -> 1
>>> B
array([[0, 1],
       [1, 0],
       [0, 1]])

And similarly for any shape:

>>> A = np.random.random_integers(0, 1, (10, 11, 12))
>>> A.shape
(10, 11, 12)
>>> B = units[A]
>>> B.shape
(10, 11, 12, 2)

You can learn more about advanced indexing on the numpy doc

Upvotes: 1

Divakar
Divakar

Reputation: 221684

Here's an approach using np.searchsorted to locate those row indices to index into the values of the dictionary and then simply indexing it to get the desired output, like so -

idx = np.searchsorted(D.keys(),A)
out = np.asarray(D.values())[idx]

Sample run -

In [45]: A
Out[45]: array([1, 2, 1])

In [46]: D
Out[46]: {1: [0, 1], 2: [1, 0]}

In [47]: idx = np.searchsorted(D.keys(),A)
    ...: out = np.asarray(D.values())[idx]
    ...: 

In [48]: out
Out[48]: 
array([[0, 1],
       [1, 0],
       [0, 1]])

Upvotes: 0

ev-br
ev-br

Reputation: 26090

>>> np.asarray([D[key] for key in A])
array([[0, 1],
       [1, 0],
       [0, 1]])

Upvotes: 0

Related Questions