简体   繁体   English

Python \\ Numpy中的数组行乘法循环

[英]Array row multiplying loop in Python\Numpy

I´m trying to multiply each row of array A by each of all the rows in another array (B) in order to get len(A) number of arrays with same number of rows and columns as the first two arrays. 我试图将数组A的每一行乘以另一个数组(B)中的所有行,以便获得len(A)个与前两个数组具有相同行数和列数的数组。

Any help? 有什么帮助吗?

pseudo-code
from numpy  import *
import numpy as np

def multipar():
    A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
    B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )
    for i in len(A):
        average = A[i]*B
    print average

multipar() 

I would like to have each resulting new array 我想要每个产生的新数组

Array C
(0.1,0.5,0.2,0.2) * (1,2,3,4);
(0.1,0.5,0.2,0.2) * (2,3,4,5);
(...)
Array D
(0.2,0.5,0.1,0.2) * (1,2,3,4);
(...)

You could do something interesting with higher dimensions. 您可以在更大的尺寸上做一些有趣的事情。 Extend either A or B into the third dimension, then multiply that with the one that wasn't extended. AB扩展到第三维,然后将其乘以未扩展的维。 eg: 例如:

A = array( [ (0.1,0.5,0.2,0.2), (0.2,0.5,0.1,0.2), (0.7,0.1,0.1,0.1) ] )
B = array( [ (1,2,3,4), (2,3,4,5), (3,4,5,6) ] )

tiled = tile (B, (3,1,1)).swapaxes (0,1)
all_results = A*tiled

Now you have all of your result arrays in all_results ; 现在,所有结果数组都在all_results you can easily get them with all_results[0] , all_results[1] , etc 您可以通过all_results[0]all_results[1]等轻松获取它们

EDIT: In response to the latest question edit: If you really need the result arrays separately, then there are two further options: 编辑:针对最新的问题编辑:如果您确实确实需要单独的结果数组,那么还有两个其他选择:

  • C, D, E = all_results
  • replace the last two statements in my first suggestion with: 将我的第一个建议中的最后两个语句替换为:

    C = B * A[0] C = B * A [0]

    D = B * A[1] D = B * A [1]

    E = B * A[2] E = B * A [2]

If you really need separate arrays for the results, and with many more rows so that a loop becomes necessary, then you can do something like (thanks @Jaime for the broadcasting notation) 如果您确实需要用于结果的单独数组,并且需要更多行,那么必须进行循环,那么您可以执行类似的操作(感谢@Jaime的广播符号)

all_results = A[:, None, :] * B[None, :, :]
for i, res in enumerate (all_results):
    locals () ['result%d'%i] = res

Now the result of multiplying by the first row is in the variable called res1 , the second row in res2 , and so forth. 现在,乘以第一行的结果在名为res1的变量中,而在第二行则在res2 ,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM