A Neater Way To Set Values At Indexes With 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.],
Solution 1:
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)] = 1v[tuple(np.r_[idx2,idx2[:,::-1]].T)] = 0
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.]])
Post a Comment for "A Neater Way To Set Values At Indexes With Numpy"