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.
我试图将值填充到一个numpy数组。该数组最初用1填充,我的目标是用另一个数组中的值覆盖指定索引处的值。
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.
我认为有一种方法可以使用OrderedDict来做到这一点,尽管我仍在试图解决这个问题。我也希望通过numpy有一个快速的方法。我希望将此示例应用于我的实际数据集,其中len(idx_pad)= 10322和len(mask)= 69268.任何帮助将不胜感激。
1 个解决方案
#1
2
This is the solution via @Divakar.
这是@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. ]
#1
2
This is the solution via @Divakar.
这是@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. ]