Python 如何为特定行和列中的numpy数组赋值

Python 如何为特定行和列中的numpy数组赋值,python,numpy,Python,Numpy,我想指定一个数组,该数组的特定值(行、列)为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 该过程是否有一些快捷方式?您可以将标签数组用作布尔数组,将fl.shape用作形状。尝试: import numpy as np fl = np.zeros((5, 3)) labels = np.ran

我想指定一个数组,该数组的特定值(行、列)为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

该过程是否有一些快捷方式?

您可以将
标签
数组用作布尔数组,将
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
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.]])

下面是另一种方法:

import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, 5)
fl[range(0, 5), labels] = 1
它将产生这个输出: