Python 比较矩阵和向量
是否有一种更简单的矢量化方法来实现与此相同的结果Python 比较矩阵和向量,python,pandas,numpy,Python,Pandas,Numpy,是否有一种更简单的矢量化方法来实现与此相同的结果 import numpy as np tempY = np.zeros((10,10)) y = np.array([0,0,2,3,4,5,5,8,8,2]).reshape(10,1) for index in range(y.size): tempY[y[index].squeeze(), index] = 1 print(tempY) 输出: [[1. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0.
import numpy as np
tempY = np.zeros((10,10))
y = np.array([0,0,2,3,4,5,5,8,8,2]).reshape(10,1)
for index in range(y.size):
tempY[y[index].squeeze(), index] = 1
print(tempY)
输出:
[[1. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
您可以将其作为行、列传递,以索引和替换值:
tempY[y.ravel(), np.arange(y.size)] = 1
tempY
array([[1., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
不是机器学习问题,请不要发送不相关的标签(已删除)。