Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy-列向量与行向量的标量乘法_Python_Vector_Matrix_Numpy - Fatal编程技术网

Python numpy-列向量与行向量的标量乘法

Python numpy-列向量与行向量的标量乘法,python,vector,matrix,numpy,Python,Vector,Matrix,Numpy,在python numpy中解决以下问题的最佳和最有效的方法是什么: 给定权重向量: weights = numpy.array([1, 5, 2]) 和一个值向量: values = numpy.array([1, 3, 10, 4, 2]) 因此,我需要一个矩阵,它在每一行上包含值向量标量乘以权重[行]: result = [ [1, 3, 10, 4, 2], [5, 15, 50, 20, 10], [2, 6, 20, 8, 4] ] 我发现的

在python numpy中解决以下问题的最佳和最有效的方法是什么:

给定权重向量:

weights = numpy.array([1, 5, 2])
和一个值向量:

values = numpy.array([1, 3, 10, 4, 2])
因此,我需要一个矩阵,它在每一行上包含
向量标量乘以
权重[行]

result = [
    [1,  3, 10,  4,  2],
    [5, 15, 50, 20, 10],
    [2,  6, 20,  8,  4]
]
我发现的一个解决方案如下:

result = numpy.array([ weights[n]*values for n in range(len(weights)) ])

有更好的方法吗?

您可以将
权重
重塑为一个维度(3,1)数组,然后将其乘以

weights = numpy.array([1, 5, 2])[:,None]  #column vector
values = numpy.array([1, 3, 10, 4, 2])
result = weights*values

print(result)

array([[ 1,  3, 10,  4,  2],  
      [ 5, 15, 50, 20, 10],  
      [ 2,  6, 20,  8,  4]])

解释
[:,None]

此操作称为。可以使用以下方法执行此操作:


美好的谢谢正是我需要的!
In [6]: numpy.outer(weights, values)
Out[6]: 
array([[ 1,  3, 10,  4,  2],
       [ 5, 15, 50, 20, 10],
       [ 2,  6, 20,  8,  4]])