问题描述
我有一个形状为 (1, m)
的 numpy 数组,每个条目 (n
) 都是一个范围为 0-9 的整数.
I have an numpy array with shape (1, m)
and each entry (n
) is an integer ranging 0-9.
我想创建一个形状为 (m, 10)
的新矩阵,其中所有条目都是 0,除了第 n 列是 1.
I want to create a new matrix that has shape (m, 10)
where all the entries are 0, except it is 1 for the nth column.
例如:
[2, 3, 1] -> [[0, 0, 1, 0, ...], [0, 0, 0, 1, ...], [0, 1, 0, 0, ...]]
我为它编写的有效代码是:
The code I wrote for it that works is:
y_values = np.array([[2, 3, 6, 4, 7]])
y = np.zeros((10, y_values.shape[1]))
for i in range(y_values.shape[1]):
y[y_values[0][i]][i] = 1
有什么方法可以摆脱 for
循环,并提高效率吗?
Is there a way I can get rid of the for
loop, and make this more efficient?
推荐答案
如您所料,有一种方法,即使用花哨的索引.您需要提供两个数组,在每个方向上给出相应的坐标.您已经拥有的列索引.每一列对应的行索引就是np.arange(m)
:
As you would expect, there is a way, using fancy indexing. You need to supply two arrays, giving the corresponding coordinates in each direction. The column index you already have. The row index, corresponding to each column, is just np.arange(m)
:
result = np.zeros((m, 10), dtype=np.bool)
result[np.arange(m), y_values[0]] = True
这篇关于在更新值的同时扩展 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!