1

I'd like to rearrange the following Numpy array:

X = [ 1.  5.  2.  4.  2.  4.  1.  5.  2.  1.  2.  1.  5.  6.  2.  6.  5.  4.
  3.  1.  4.  6.  5.  3.  1.  5.  4.  5.  3.  3.  1.  4.  4.  5.  4.  4.
  3.  6.  1.  5.  4.  1.  4.  4.  1.  5.  1.  2.  1.  4.  6.  1.  3.  4.
  1.  6.  3.  1.  1.  5.  6.  4.  5.  2.  6.  3.  1.  3.  4.  6.  3.  2.
  1.  4.  2.  4.  2.  1.  2.  2.  1.  1.  6.  4.  3.  6.  1.  1.  4.  1.
  4.  4. nan nan nan nan]

by the following sequence 3, 2, 6, 5, 4, 1.

Essentially, the entire array is arranged such that all the 3's come first, 2's, 6's, 5's, 4's and finally 1's. What is the best way to do this, while retaining the Numpy array instead of turning it into a list?

2

1 Answer 1

1

Using list.index:

ind = [3, 2, 6, 5, 4, 1]
sorted(X, key=lambda x : ind.index(x) if x in ind else -1)

Output:

[nan,
 nan,
 nan,
 nan,
 3,
 ...
 1,
 1,
 1]

If you want nan to come at last:

last = len(ind)
sorted(X, key=lambda x : ind.index(x) if x in ind else last)

Output:

[3,
 3,
 ...
 1,
 1,
 nan,
 nan,
 nan,
 nan]
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Chris, thank you! Is there a way of retaining the object type such that it is a numpy array rather than a list?
@MichikoC You can always wrap sorted(...) with np.array: np.array(sorted(X, key = ...))
Thanks, I tried that, but it seems that key can't be something like ind = [3, 2, 6, 5, 4, 1] though?
You mean without using lambda? No you need to use ind inside of lambda just like in the answer ;)
Oh! I apologize - I meant, I tried using np.array(sorted(X, key = ...)) but it seems key can't be something like key = ind.
|

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.