mike
mike

Reputation: 23811

Specify Order numpy array

I'm trying to put an array in the order of another array. For example, if I have:

arr1 = np.array(['a', 'b', 'c'])
index = np.array([2, 1, 0])

My desired outcome, arr2, is ['c', 'b', 'a'], such that:

arr2[index[i]] == arr1[i]

Upvotes: 1

Views: 159

Answers (2)

gcbirzan
gcbirzan

Reputation: 1514

Try this:

[arr1[i] for i in index]

Upvotes: 1

jterrace
jterrace

Reputation: 67063

You can simply pass the selector array as index to the character array:

>>> import numpy as np
>>> arr1 = np.array(['a', 'b', 'c'])
>>> index = np.array([2, 1, 0])
>>> arr1[index]
array(['c', 'b', 'a'], 
      dtype='|S1')

Upvotes: 6

Related Questions