0

I'm very new to python so i would appreciate any help I can get. How can I rearrange A to look like B?

A=([3,5,6,9,0,0,0,0,0])
B=([0,0,3,0,5,6,0,0,9])

Specifically, I want to rearrange A using the the entries as an index. So I want the 3rd, 5th, 6th, and 9th elements of B to be the value of that index.

2 Answers 2

4

Since this is tagged numpy, here's a numpy solution:

In [11]: A = np.array([3,5,6,9,0,0,0,0,0])

Extract the poisition of the nonzero elements in A:

In [12]: np.nonzero(A)[0]
Out[12]: array([0, 1, 2, 3])

In [13]: ind = A[np.nonzero(A)[0]]

Trimming the zeroes may be equivalent (depending on the rules of the game):

In [14]: np.trim_zeros(A)
Out[14]: array([3, 5, 6, 9])

Create a B of zeroes and then fill with ind:

In [15]: B = np.zeros(A.max() + 1)

In [16]: B[ind] = ind

In [17]: B
Out[17]: array([ 0.,  0.,  0.,  3.,  0.,  5.,  6.,  0.,  0.,  9.])
Sign up to request clarification or add additional context in comments.

5 Comments

depending on rules (and the solution you want), A.max() may be len(A) instead.
To match the OP's desired result, I think you need B = B[1:].
Good catch, could also fix using B = np.zeros(A.max()) and B[ind - 1] = ind.
Thank you very much for the solution! Appreciate a solution without a loop. I did want the solution with len(A) instead of A.max(). If i skip a few steps and do B[A-1]=A] I get the same answer, but if I use len(A) instead of A.max(), then the last element in B becomes 0 instead of 9. Can you explain why this happens?
in python (numpy/C etc.) indexing starts at 0 (so we get off by one errors trying to get what you want, indexing starting at 1). np.zeros creates an array of the length you pass it, so try with len(A) - 1...?
2

I assume that you don't have any duplicate element in A or the element that is larger than the length of the list A. Then, using list comprehension,

B = [ i if i in A else 0 for i in range(1,10) ]

would work.


Explanation:

First, a list comprehension

[i for i in range(1,10)]

gives [1, 2, 3, 4, 5, 6, 7, 8, 9]. You want to put 0 if an element in this list does not belong to the list A. Thus, you replace the first i in the list comprehension to i if i in A else 0. It means that i is left alone if it belongs to A, orelse substitute 0.

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.