1

I am trying to pad values to a numpy array. The array is initially filled with ones, and my goal is to overwrite the values of ones at specified indices with values from another array.

import numpy as np
# get initial array of ones
mask = np.ones(10)
# get values to overwrite ones at indices
values = [10, 30, 50.5]
# get indices for which values will replace ones 
idx_pad = [1, 6, 7]

print(mask)
>> [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

What I want to get is:

>> [ 1  10  1  1  1  1  30  50.5  1  1 ]

I think there's a way to do this using an OrderedDict, though I'm still trying to figure it out. I'm also hopeful that there is a fast approach via numpy. I hope to apply this example to my actual dataset, for which len(idx_pad) = 10322 and len(mask) = 69268. Any help would be appreciated.

4

1 回答 1

2

这是通过@Divakar 的解决方案。

import numpy as np
# get initial array of ones
mask = np.ones(10)
# get values to overwrite ones at indices
values = [10, 30, 50.5]
# get indices for which values will replace ones
idx_pad = [1, 6, 7]

print(mask)
>> [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]

# replace values at indices in idx_pad
mask[idx_pad] = values

print(mask)
>> [  1.   10.    1.    1.    1.    1.   30.   50.5   1.    1. ]
于 2017-06-26T21:52:00.640 回答