2

I have a numpy array A and B.

A = [ 1, 2, 5, 9.8, 55, 3]
B = [ 3, 4] 

Now, how to remove A[3] & A[4] that is whatever indices array B is having and then put them at the start of array A. So, I want my output to be

A = [9.8, 55, 1, 2, 5,  3]

Note : Both A and B are numpy arrays.

Any help is highly appreciated.

1
  • Did either of the posted solutions work for you? Commented Mar 23, 2017 at 17:17

2 Answers 2

1

One approach with boolean-indexing would be -

mask = np.in1d(np.arange(A.size),B)
out = np.r_[A[mask], A[~mask]]

Sample run -

In [26]: A = np.array([ 1, 2, 5, 9.8, 55, 3])

In [27]: B = np.array([ 3, 4])

In [28]: mask = np.in1d(np.arange(A.size),B)

In [29]: np.r_[A[mask], A[~mask]]
Out[29]: array([  9.8,  55. ,   1. ,   2. ,   5. ,   3. ])

Another with integer-indexing -

idx = np.setdiff1d(np.arange(A.size),B)
out = np.r_[A[B], A[idx]]

Sample run -

In [36]: idx = np.setdiff1d(np.arange(A.size),B)

In [37]: np.r_[A[B], A[idx]]
Out[37]: array([  9.8,  55. ,   1. ,   2. ,   5. ,   3. ])
Sign up to request clarification or add additional context in comments.

Comments

0

Non-numpy answer.

A = [ 1, 2, 5, 9.8, 55, 3]
B = [ 3, 4]
new_arr = [A[i] for i in B if i<len(A)] + [A[i] for i in range(len(A)) if i not in set(B)]
# [9.8, 55, 1, 2, 5, 3]

You may remove the extra check if i<len(A) if you are sure about it.

Comments

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.