同时更改python numpy数组元素 [英] Simultaneous changing of python numpy array elements
问题描述
我有一个范围为[0,3]的整数向量,例如:
I have a vector of integers from range [0,3], for example:
v = [0,0,1,2,1,3, 0,3,0,2,1,1,0,2,0,3,2,1]
.
我知道我可以使用以下
v[v == 0] = 5
将向量v中0
的所有出现更改为值5
.
但是我想做些不同的事情-我想将0
的所有值(我们称它们为target values
)更改为1
,并且将所有值从0
更改为0
,因此我想获得以下信息:
which changes all appearences of 0
in vector v to value 5
.
But I would like to do something a little bit different - I want to change all values of 0
(let's call them target values
) to 1
, and all values different from 0
to 0
, thus I want to obtain the following:
v = [1,1,0,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0]
但是,我不能按以下方式调用替换代码(我在上面使用过):
However, I cannot call the substitution code (which I used above) as follows:
v[v==0] = 1
v[v!=0] = 0
因为这显然导致了零向量. 是否可以通过并行方式进行上述替换,以获得所需的矢量? (我想拥有一种通用技术,即使我更改目标值也可以使用它).任何建议都将非常有帮助!
because this obviously leeds to a vector of zeros. Is it possible to do the above substitution in a parralel way, to obtain the desired vector? (I want to have a universal technique, which will allow me to use it even if I will change what is my target value). Any suggestions will be very helpful!
推荐答案
您可以检查v
是否等于零,然后将布尔数组转换为int,因此,如果原始值为零,则布尔值为true并转换为1,否则为0:
You can check if v
is equal to zero and then convert the boolean array to int, and so if the original value is zero, the boolean is true and converts to 1, otherwise 0:
v = np.array([0,0,1,2,1,3, 0,3,0,2,1,1,0,2,0,3,2,1])
(v == 0).astype(int)
# array([1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0])
或使用numpy.where
:
np.where(v == 0, 1, 0)
# array([1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0])
这篇关于同时更改python numpy数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!