[英]modifying values in numpy array
Let's suppose a
and b
are given as below:- 假设
a
和b
给出如下:
a = np.arange(5)
b = [0,1,2]
What I want is that for indices excluding those in b
,values in a
should be equal to -1. 我要的是,不包括在指数
b
,在值a
应等于-1。 So in the above case a
will be equal to 因此,在上述情况下,
a
等于
a = array([0, 1, 2, -1, -1])
There is a method which I am aware of ie 我知道一种方法,即
a[list(set(a)-set(b))] = -1
but takes too much time, and leads to too much complexity when actually writing the code. 但是会花费太多时间,并且在实际编写代码时会导致太多复杂性。 As always I am looking out for better methods than the above one.
一如既往,我一直在寻找比上述方法更好的方法。 Feel free to use any tools required.
随意使用所需的任何工具。 Another example (just in case):- if
另一个例子(以防万一):-如果
a = np.arange(12)
b = [3,5,6]
Then what I really want is a = array([-1, -1, -1, 3, -1, 5, 6, -1, -1, -1, -1, -1])
PS Don't worry a
will always be of the form np.arange(int)
and no value of b
exceeds the length of a
然后,我真正想要的是
a = array([-1, -1, -1, 3, -1, 5, 6, -1, -1, -1, -1, -1])
PS别担心a
将始终是这样的形式np.arange(int)
和没有的值b
超过的长度a
>>> a = np.arange(12)
>>> b = [3,5,6]
>>> a[~np.in1d(np.arange(len(a)), b)] = -1
>>> a
array([-1, -1, -1, 3, -1, 5, 6, -1, -1, -1, -1, -1])
Well if the object is to create a range of values that are either the same as their index or -1 then it might be simpler to start with all -1 and add the data you want rather than the other way around. 好吧,如果对象要创建与其索引相同或等于-1的值的范围,则从所有-1开始并添加所需的数据可能会更简单,而不是相反。
>>> a = np.full(12, -1, dtype=int)
>>> b = [3, 5, 6]
>>> a[b] = b
>>> a
array([-1, -1, -1, 3, -1, 5, 6, -1, -1, -1, -1, -1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.