Ale*_*azo 5 python arrays numpy matrix-indexing
我有一个用零填充的NxM numpy数组和一个大小为N的1D numpy数组,大小在0到M-1之间。如您所见,数组的维数与矩阵中的行数匹配。整数数组中的每个元素意味着必须将其对应行中给定位置的位置设置为1。例如:
# The matrix to be modified
a = np.zeros((2,10))
# Indices array of size N
indices = np.array([1,4])
# Indexing, the result must be
a = a[at indices per row]
print a
[[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]]
Run Code Online (Sandbox Code Playgroud)
我尝试使用索引,a[:,indices]但是这为每一行设置了相同的索引,最终这为所有行设置了索引。如何将给定索引设置为每行 1 个?
使用np.arange(N)为了寻址行和列的索引:
>>> a[np.arange(2),indices] = 1
>>> a
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)
要么:
>>> a[np.where(indices)+(indices,)] = 1
>>> a
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
Run Code Online (Sandbox Code Playgroud)