Pandas: how to multiply each element of a Series to each element of a column in a Dataframe

Viewed 313

I am trying to find a solution to do the following operation using either numpy or pandas:

enter image description here

For instance, the result matrix has [0, 0, 0] as its first column which is a result of [a x a] elementwise, more specifically it is equal to: [0 x 0.5, 0 x 0.4, 0 x 0.1].

If there is no solution method for such a problem, I might just expand the series to a dataframe by duplicating its values to just multiply two dataframes..

input data:

series = pd.Series([0,10,0,100,1], index=list('abcde'))

df = pd.DataFrame([[0.5,0.4,0.2,0.7,0.8],
                   [0.4,0.5,0.1,0.1,0.5],
                   [0.1,0.9,0.8,0.3,0.8]
                  ], columns=list('abcde'))
1 Answers

This is actually very simple. Because the Series' index aligns with the DataFrame's columns, you only need to do:

series*df

output:

     a    b    c     d    e
0  0.0  4.0  0.0  70.0  0.8
1  0.0  5.0  0.0  10.0  0.5
2  0.0  9.0  0.0  30.0  0.8

input:

series = pd.Series([0,10,0,100,1], index=list('abcde'))
df = pd.DataFrame([[0.5,0.4,0.2,0.7,0.8],
                   [0.4,0.5,0.1,0.1,0.5],
                   [0.1,0.9,0.8,0.3,0.8]
                  ], columns=list('abcde'))
Related