[英]Numpy replace values in array using putmask and indexing
I would like to replace values in a NumpyArray, in only one column, on several selected rows only, using putmask.我想使用 putmask 替换 NumpyArray 中的值,仅在一列中,仅在几个选定的行上。 I wish to use indexing on the array to be modified as well as the mask used.
我希望对要修改的数组以及使用的掩码使用索引。 Therefor I create a nd.array, a mask and and array of desired replacements.
因此,我创建了一个 nd.array、一个掩码和所需的替换数组。 as follows:
如下:
import numpy as np
a = np.linspace(1,30,30)
a.shape(10,3)
mask = np.random.randint(2, size=8)
replacements = a[[2,4,5,6,7,8],0]*a[[2,4,5,6,7,8],1]
a
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10., 11., 12.],
[13., 14., 15.],
[16., 17., 18.],
[19., 20., 21.],
[22., 23., 24.],
[25., 26., 27.],
[28., 29., 30.]])
mask
array([0, 1, 0, 0, 1, 0, 1, 1])
replacements
array([ 56., 182., 272., 380., 506., 650.])
np.putmask(a[[2,4,5,6,7,8],2], mask[2::], replacements)
My expected result would look like this:我的预期结果如下所示:
a
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10., 11., 12.],
[13., 14., 15.],
[16., 17., 272.],
[19., 20., 21.],
[22., 23., 506.],
[25., 26., 650.],
[28., 29., 30.]])
But instead I get this:但是我得到了这个:
a
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.],
[10., 11., 12.],
[13., 14., 15.],
[16., 17., 18.],
[19., 20., 21.],
[22., 23., 24.],
[25., 26., 27.],
[28., 29., 30.]])
Anybody has an idea maybe?有人有想法吗?
Note that you are using fancy indexing, so when using np.putmask
you are modifying a copy
rather than a sliced view , and thus the original array remains unchanged.请注意,您使用的是花哨的索引,因此在使用
np.putmask
您正在修改copy
而不是 切片视图,因此原始数组保持不变。 You can check this by trying to index using slice notation, np.putmask(a[2:8,2], mask[2::], replacements)
for instance, which would in this case modify the values in a
.您可以通过使用切片表示法,试图索引检查这个
np.putmask(a[2:8,2], mask[2::], replacements)
例如,这会在这种情况下,修改的值a
。
What you could do is use np.where
and reassign the values to the corresponding indices in a
:你可以做的是使用
np.where
并重新分配值在相应的指标a
:
a[[2,4,5,6,7,8],2] = np.where(mask[2::], replacements, a[[2,4,5,6,7,8],2])
Output
输出
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 56.],
[ 10., 11., 12.],
[ 13., 14., 182.],
[ 16., 17., 272.],
[ 19., 20., 380.],
[ 22., 23., 506.],
[ 25., 26., 650.],
[ 28., 29., 30.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.