2

I have the following numpy array a = np.array([1,1,2,1,3]) that should be transformed into the following array b = np.array([1,1,1,1,1,1,1,1]).

What happens is that all the non 1 values in the a array should be expanded in the b array to their multiple defined in the a array. Simpler said, the 2 should become 2 ones, and the 3 should become 3 ones.

Frankly, I couldn't find a numpy function that does this, but I'm sure one exists. Any advice would be very welcome! Thank you!

2
  • look at np.repeat Commented Nov 8, 2019 at 19:38
  • @Divakar, oh my god ... My mind must have been on holiday. Thank you, more than happy to accept your answer. Commented Nov 8, 2019 at 19:47

3 Answers 3

2

We can simply do -

np.ones(a.sum(),dtype=int)

This will accomodate all numbers : 1s and non-1s, because of the summing and hence give us the desired output.

Sign up to request clarification or add additional context in comments.

Comments

1
In [71]: np.ones(len(a),int).repeat(a)                                          
Out[71]: array([1, 1, 1, 1, 1, 1, 1, 1])

For this small example it is faster than np.ones(a.sum(),int), but it doesn't scale quite as well. But overall both are fast.

Comments

0

Here's one possible way based on the number you wanna be repeated:

In [12]: a = np.array([1,1,2,1,3])
In [13]: mask = a != 1
In [14]: np.concatenate((a[~mask], np.repeat(1, np.prod(a[mask]))))
Out[14]: array([1, 1, 1, 1, 1, 1, 1, 1, 1])

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.