0

I have following numpy arrays:

 whole = np.array(
 [1, 0, 3, 0, 6]
 )
 sparse = np.array(
 [9, 8]
 )

Now I want to replace every zero in the whole array in chronological order with the items in the sparse array. In the example my desired array would look like:

 merged = np.array(
 [1, 9, 3, 8, 6]
 )

I could write a small algorithm by myself to fix this but if someone knows a time efficient way to solve this I would be very grateful for you help!

asked Aug 5, 2020 at 18:45
3
  • Are you sure the number of 0s match with the sparse? Commented Aug 5, 2020 at 18:49
  • 2
    ...since you could just write whole[whole==0] = sparse then Commented Aug 5, 2020 at 18:51
  • Yes! Awesome, that was exactly what I was looking for. Thank you very much. Commented Aug 5, 2020 at 18:54

1 Answer 1

2

Do you assume that sparse has the same length as there is zeros in whole ?

If so, you can do:

import numpy as np
from copy import copy
whole = np.array([1, 0, 3, 0, 6])
sparse = np.array([9, 8])
merge = copy(whole)
merge[whole == 0] = sparse

if the lengths mismatch, you have to restrict to the correct length using len(...) and slicing.

Dharman
33.9k27 gold badges103 silver badges153 bronze badges
answered Aug 5, 2020 at 18:59

4 Comments

I was outdated by the comment above, but my method doesn't change 'whole' array in place.
Would it be inplace without the copy? I am a little confused about the purpose of the copy.
You should use numpy's copy as opposed to copy.copy
To Kevin : if I don't use copy, when I update 'merge', the original array 'whole' is modified the same way'. So one has to copy the numpy array to keep the original data

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.