如何在特定行列为numpy数组分配值

3
我希望能够在特定的行和列中分配一个值为1的数组。
以下是我的代码:
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, (5, 1))
for i in range(5):
    fl[i, labels[i]] = 1

有没有这个过程的快捷方式?
2个回答

1
你可以将 labels 数组视为布尔数组,并使用 fl.shape 作为形状。尝试以下代码:
import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 1, fl.shape).astype(bool)
fl[labels] = 1

以下是labels和result中布尔数组的样式:
>>> labels
array([[False,  True, False],
   [ True,  True, False],
   [False,  True,  True],
   [ True,  True,  True],
   [ True, False, False]], dtype=bool)

>>> fl
array([[ 0.,  1.,  0.],
   [ 1.,  1.,  0.],
   [ 0.,  1.,  1.],
   [ 1.,  1.,  1.],
   [ 1.,  0.,  0.]])

1
这是另一种方法来做它:

import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, 5)
fl[range(0, 5), labels] = 1

而它将产生以下输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接