pandas /Python逐行相乘 [英] Pandas/Python multiply columns by row
问题描述
很抱歉,如果这是一个简单的问题.
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.
我使用了df.multiply()并继续为所有值获取NaN,这可能是因为两个df的长度不匹配.
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
推荐答案
您可以使用 mul
,由iloc
:
You can use mul
by first row of df1
selected by iloc
:
print (df2.mul(df1.iloc[0]))
示例:
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
这篇关于 pandas /Python逐行相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!