Home > Enterprise >  List of scalars times a vector in python. Linear algebra Python
List of scalars times a vector in python. Linear algebra Python

Time:06-09

I am trying to solve a problem in pandas. I have written a loop for it but its not giving me the desired result.

I have a some scalar values a = [1,2], and I have a vector b = [1,2,3,4]. I would like to perform element wise multiplication on a and b - so a[0]* b, a[1]*b..

df = []
a = [1,2]
b = [1,2,3,4]

for i in a:
    for j in b:
        test = i * j
        df.append(test)

now in df I have df = (1,2,3,4,2,3,6,8) which is technically correct but I would like to treat a list of scalars to iterate over, so my result is

[1,2,3,4][2,4,6,8] - that can be saved in the dataframe df

CodePudding user response:

use outer:

np.outer(a, b)
 
array([[1, 2, 3, 4],
       [2, 4, 6, 8]])

CodePudding user response:

Another answer is using einsum:

np.einsum('i,j->ij',a,b)

CodePudding user response:

You can use broadcasting for multiple lists converted to arrays:

out = np.array(a)[:, None] * np.array(b)
print (out)
[[1 2 3 4]
 [2 4 6 8]]
  • Related