假设我有一个数组
np.zeros((4,2))
我有一个值列表[4,3,2,1]
,我想将其分配到以下位置:[(0,0),(1,1),(2,1),(3,0)]
如何在不使用for循环或将数组展平的情况下完成?
我可以使用花式索引来检索值,但无法将它们分配。
======更新=========
感谢@hpaulj,我意识到原始代码中的错误是什么。
当我使用zeros_like
初始化数组时,默认为int
并截断值。因此,看起来我没有分配任何内容!
您可以使用元组索引:
>>> import numpy as np
>>> a = np.zeros((4,2))
>>> vals = [4,3,2,1]
>>> pos = [(0,0),(1,1),(2,0),(3,1)]
>>> rows, cols = zip(*pos)
>>> a[rows, cols] = vals
>>> a
array([[ 4., 0.],
[ 0., 3.],
[ 2., 0.],
[ 0., 1.]])
zeros_like
时要注意数据类型。将浮点数赋值给整数槽位会截断值。 - hpauljnp.transpose
会自动将Python元组列表转换为NumPy数组,并对其进行转置。 tuple
将索引坐标转换为元组,这样做是因为在NumPy中a[rows, cols]
等同于a[(rows, cols)]
。import numpy as np
a = np.zeros((4, 2))
vals = range(4)
indices = [(0, 0), (1, 1), (2, 0), (3, 1)]
a[tuple(np.transpose(indices))] = vals
print(a)
arr[idx[:,0], idx[:,1]] = [4,3,2,1]
,其中idx = np.array([[0,0],[1,1],[2,2],[3,1]])
? - Divakar(2,2)
超出了原始数组的范围。 - wima[[0,1,2,3], [0,1,2,1]] = 4,3,2,1
。 - Paul Panzer