使用NumPy在索引处设置值的更简洁方法 [英] A neater way to set values at indexes with NumPy
问题描述
我最初有零的numpy数组,如下所示:
I have a numpy array initially with zeros, like this:
v = np.zeros((5, 5))
v
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
我也有一组数组 idx1
和 idx2
。
idx1
array([[0, 3],
[0, 4],
[1, 3],
[2, 4]])
idx2
array([[0, 1],
[0, 2],
[0, 4],
[1, 3]])
将每对值视为行和列索引。因此,例如,在 idx1
中,第一对(0,3)
将成为<$ c $的索引器c> v [0,3] 依此类推。
Look upon each pair of values as row and column indices. So, for example, in idx1
, the first pair (0, 3)
would be indexers into v[0, 3]
and so on.
我想先在指定的索引处设置值idx1
到 1
,然后是 idx2
指定的所有索引到 0
。
I want to first set values at indexes specified by idx1
to 1
, followed by all indexes specified by idx2
to 0
.
另外,请注意,如果某个阵列中有一对(i,j)
,我想要同时设置 v [i,j]
和 v [j,i]
。
Also, please note that if there is a pair (i, j)
in some array, I want to set v[i, j]
and v[j, i]
at the same time.
我的最终结果变为:
array([[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1.],
[ 1., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.]])
我目前通过以下方式实现这一目标:
I currently achieve this by doing:
def set_vals(x, i, j, v):
x[i, j] = x.T[i, j] = v
v = np.zeros((5, 5))
i1, j1 = idx1[:, 0], idx1[:, 1]
i2, j2 = idx2[:, 0], idx2[:, 1]
set_vals(v, i1, j1, 1)
set_vals(v, i2, j2, 0)
v # the result
但是,我相信可能有更好的方法。很想听到任何改进的想法/建议。谢谢!
However, I believe there might be a better way. Would love to hear any thoughts/suggestions for improvement. Thanks!
推荐答案
为了寻找更紧凑的表达方式,我得到了这个 -
In search of a more "compact" way of expressing it, I got this -
v = np.zeros((5, 5))
v[tuple(np.r_[idx1,idx1[:,::-1]].T)] = 1
v[tuple(np.r_[idx2,idx2[:,::-1]].T)] = 0
在python3.6 +上,你可以使用 *
解包运算符以进一步减少此值:
On python3.6+, you can use the *
unpacking operator to reduce this further:
v[[*np.r_[idx1,idx1[:,::-1]].T]] = 1
v[[*np.r_[idx2,idx2[:,::-1]].T]] = 0
v
array([[ 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 1.],
[ 1., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.]])
这篇关于使用NumPy在索引处设置值的更简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!