我在2D数组中设置多个元素的值,但是我的数据有时包含给定索引的多个值.
似乎总是分配"后来的"值(参见下面的示例),但这种行为是否得到保证,或者我有可能得到不一致的结果?我怎么知道我可以在矢量化作业中以"我想要的方式"解释"以后"?
即在我的第一个例子a肯定会包含4,在第二个例子中它会打印values[0]吗?
很简单的例子:
import numpy as np
indices = np.zeros(5,dtype=np.int)
a[indices] = np.arange(5)
a # array([4])
Run Code Online (Sandbox Code Playgroud)
另一个例子
import numpy as np
grid = np.zeros((1000, 800))
# generate indices and values
xs = np.random.randint(0, grid.shape[0], 100)
ys = np.random.randint(0, grid.shape[1], 100)
values = np.random.rand(100)
# make sure we have a duplicate index
print values[0], values[5]
xs[0] = xs[5]
ys[0] = ys[5]
grid[xs, ys] = values
print "output value is", grid[xs[0], ys[0]]
# always prints …Run Code Online (Sandbox Code Playgroud) 基本问题是:在做什么时会发生什么a[i] += b?
鉴于以下内容:
import numpy as np
a = np.arange(4)
i = a > 0
i
= array([False, True, True, True], dtype=bool)
Run Code Online (Sandbox Code Playgroud)
我明白那个:
a[i] = x是相同的a.__setitem__(i, x),它直接分配给指示的项目ia += x是一样的a.__iadd__(x),它不到位此外但是当我这样做时会发生什么:
a[i] += x
Run Code Online (Sandbox Code Playgroud)
特别:
a[i] = a[i] + x吗?(这不是就地操作)i是:
int指数,或ndarray,或slice对象背景
我开始深入研究这个问题的原因是我在处理重复索引时遇到了非直观的行为:
a = np.zeros(4)
x = np.arange(4)
indices = np.zeros(4,dtype=np.int) # duplicate indices
a[indices] …Run Code Online (Sandbox Code Playgroud) 假设我有2个矩阵M和N(都有> 1列).我还有一个索引矩阵I,有2列 - 1表示M,1表示N.N的索引是唯一的,但M的索引可能出现不止一次.我想要执行的操作是,
for i,j in w:
M[i] += N[j]
Run Code Online (Sandbox Code Playgroud)
除了for循环之外,还有更有效的方法吗?
假设你有以下代码
a = np.ones(8)
pos = np.array([1, 3, 5, 3])
a[pos] # returns array([ 1., 1., 1., 1.]), where the 2nd and 4th el are the same
a[pos] +=1
Run Code Online (Sandbox Code Playgroud)
最后一条指令返回
array([ 1., 2., 1., 2., 1., 2., 1., 1.])
Run Code Online (Sandbox Code Playgroud)
但我希望对相同索引的分配进行总结,以便获得
array([ 1., 2., 1., 3., 1., 2., 1., 1.])
Run Code Online (Sandbox Code Playgroud)
有人已经经历过同样的情况吗?