Pandas/Python multiply columns by row

2020-04-21 07:15发布

Apologies if this is a simple question.

I have two dataframes each with the same columns. I need to multiply each row in the second dataframe by the only row in the first.

Eventually there will be more columns of different ages so I do not want to just multiply by a scalar.

I have used df.multiply() and continue to get NaN for all values presumably because the two df are not matched in length.

Is there a way to multiply each row in one dataframe by a singular row in another?

age   51200000.0  70000000.0
SFH
0        0.75        0.25

.

age             51200000.0    70000000.0
Lambda                                 
91.0       0.000000e+00  0.000000e+00
94.0       0.000000e+00  0.000000e+00
96.0       0.000000e+00  0.000000e+00
98.0       0.000000e+00  0.000000e+00
100.0      0.000000e+00  0.000000e+00
102.0      0.000000e+00  0.000000e+00
...        ...           ...
1600000.0  1.127428e+22  8.677663e+21

1条回答
何必那么认真
2楼-- · 2020-04-21 08:12

You can use mul by first row of df1 selected by iloc:

print (df2.mul(df1.iloc[0]))

Sample:

print (df1)
      51200000.0  70000000.0
age                        
0          0.75        0.25

print (df2)
      51200000.0  70000000.0
age                         
91.0         1.0         2.0
94.0         5.0        10.0
96.0         0.0         0.0

print (df2.mul(df1.iloc[0]))
      51200000.0  70000000.0
age                         
91.0        0.75         0.5
94.0        3.75         2.5
96.0        0.00         0.0
查看更多
登录 后发表回答