简体   繁体   中英

Multiply each value in a column by a row python

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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