1

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]

2 Answers 2

6

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps there's an error in my code, but when I run this I get the following relationship, not the desired one: arr2[i] == arr1[index[i]]
I think the issue might be a few lines before in the code -- thanks!
1

Try this:

[arr1[i] for i in index]

1 Comment

Doesn't return an array and is inefficient for numpy arrays. General rule: Don't treat numpy arrays as python lists. There is almost always a better way to do it with numpy builtins.

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.