Home > Enterprise >  Multiply each value in a column by a row python
Multiply each value in a column by a row python

Time:06-24

I have a small subset of data here:

import pandas as pd

days = [1, 2, 3]

time = [2, 4, 2, 4, 2, 4, 2, 4, 2]

df1 = pd.DataFrame(days)

df2 = pd.Series(time)

df2 = df2.transpose()

df3 = df1*df2

Df1 is a column of data and df2 is a row of data. I need a dataframe that is going to be 3x9 where the row is multiplied by each value in the column to make one large dataframe. The end result should look like:

df3 = [2  4  2  4  2  4  2  4  2
       4  8  4  8  4  8  4  8  4
       6  12 6  12 6  12 6  12 6 ]

They way I currently have it for my larger dataset, only a few datapoints are correctly multiplied and most are nans.

CodePudding user response:

Dot(product) is one of the solutions to this problem

import pandas as pd
days = [1, 2, 3]
time = [2, 4, 2, 4, 2, 4, 2, 4, 2]
df1 = pd.DataFrame(days)
df2 = pd.DataFrame(time)
# use dot 
df3 = df1.dot(df2.T)
df3

Output

0   1   2   3   4   5   6   7   8
0   2   4   2   4   2   4   2   4   2
1   4   8   4   8   4   8   4   8   4
2   6   12  6   12  6   12  6   12  6

CodePudding user response:

Try this:

df1.dot(df2.to_frame().T)

Output:

   0   1  2   3  4   5  6   7  8
0  2   4  2   4  2   4  2   4  2
1  4   8  4   8  4   8  4   8  4
2  6  12  6  12  6  12  6  12  6
  • Related