Python numpy更新数组索引
我有以下指数Python numpy更新数组索引,python,arrays,numpy,Python,Arrays,Numpy,我有以下指数 indices = array([[ 0, 0], [ 1, 1], [ 5, 3], [ 7, 9]]) 我想用这些索引更新一个2d numpy数组 img = np.zeros((12,12), np.uint8) 我尝试了以下方法 img[indices] = 1 indices_x = indices[:, 0] indices_y = indices[:, 1] img[np.ix_(indices_x,indices_y)] = 1 尝试
indices = array([[ 0, 0],
[ 1, 1],
[ 5, 3],
[ 7, 9]])
我想用这些索引更新一个2d numpy数组
img = np.zeros((12,12), np.uint8)
我尝试了以下方法
img[indices] = 1
indices_x = indices[:, 0]
indices_y = indices[:, 1]
img[np.ix_(indices_x,indices_y)] = 1
尝试分别指定x和y索引
In [0]: img[indices[:,0], indices[:,1]] = 3
In [1]: img
Out[1]:
array([[3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 3, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 3, 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, 0, 0, 0, 0, 3, 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, 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]], dtype=uint8)
或者,您可以提供一个元组或列表:
In [2]: new_inds = tuple(zip(*indices))
In [3]: new_inds
Out[3]: ((0, 1, 5, 7), (0, 1, 3, 9))
In [4]: img[new_inds] = 4
In [5]: img
Out[5]:
array([[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 4, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 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, 0, 0, 0, 0, 4, 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, 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]], dtype=uint8)
像这样
img[index[:,0],index[:,1]=1
谢谢coldspeed。因为名声不好,所以不能提高投票率。其中一件事和另一件不一样。谢谢奥利弗。由于声望低,无法投票