[英]How to assign value to a scalar variable in numpy array?
I wrote a for-loop
and wished to assign the value to the first variable in the part of an array that equals to -inf
. 我编写了一个
for-loop
,希望将值分配给等于-inf
的数组部分中的第一个变量。 The complete code is as below: 完整的代码如下:
cList = np.full((5), -np.inf)
for i in range(5):
newest = another_array[i][1]
cList[cList==-np.inf][0] = newest
The code didn't throw any errors. 该代码没有引发任何错误。 However the value assignment was failed.
但是,值分配失败。 Do you have any idea about it?
你有什么想法吗? Thanks in advance!
提前致谢!
This: 这个:
cList[cList==-np.inf]
makes a copy of the selected data, not a view, so this: 复制所选数据而不是视图,因此:
cList[cList==-np.inf][0] = newest
modifies the copy, leaving cList
unchanged. 修改副本,而
cList
保持不变。
Repeatedly searching cList
for instances of -inf
is a really inefficient way to go about this. 反复在
cList
中搜索cList
的实例是-inf
的一种非常低效的方法。 The best solution will depend on the details of your program. 最好的解决方案将取决于您的程序的详细信息。 For the simple example you've posted, you could just do
对于您发布的简单示例,您可以
c = another_array[:5, 1].copy() # or just another_array[:5, 1] if a view is fine
For more complex cases, you might want to create an array of values to assign and do 对于更复杂的情况,您可能需要创建一个值数组来分配和执行
c[c == -np.inf] = values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.