[英]How to get a 2D NumPy array with value 1 at indices represented by values in 1D NumPy array (Python)
How to get a 2D np.array with value 1 at indices represented by values in 1D np.array in Python.如何在 Python 中的 1D np.array 中的值表示的索引处获取值为 1 的 2D np.array。
Example:例子:
[1, 2, 5, 1, 2]
should be converted to应转换为
[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0]]
Here you already know the width (shape[2]) value of the new array beforehand.在这里,您已经预先知道新数组的宽度 (shape[2]) 值。
I can do it manually but is there any way to do it directly using NumPy methods for faster execution?我可以手动完成,但是有什么方法可以直接使用 NumPy 方法来加快执行速度吗? The dimension of my array is quite large and I have to do this for all iteration.我的数组的维度非常大,我必须在所有迭代中都这样做。 Thus, doing this manually for each iteration is quite computationally demanding.因此,为每次迭代手动执行此操作在计算上要求很高。
You can create a array with zeros using np.zeros
.您可以使用np.zeros
创建一个包含零的数组。 The shape the array should be (len(1D array), max(1D array)+1)
.数组的形状应该是(len(1D array), max(1D array)+1)
。 Then use NumPy's indexing.然后使用 NumPy 的索引。
idx = [1, 2, 5, 1, 2]
shape = (len(idx), max(idx)+1)
out = np.zeros(shape)
out[np.arange(len(idx)), idx] = 1
print(out)
[[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1.]
[0. 1. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.