简体   繁体   中英

Fill numpy array with other numpy array

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM