[英]How to multiply each column in a dataframe with a row from another dataframe pandas?
I have two dataframes shown below;我有两个数据框如下所示; I want to multiply each column of df1 with each value in the corresponding row in df2.我想将 df1 的每一列与 df2 中相应行中的每个值相乘。 Each time should produce a new column.每次都应该产生一个新列。 (It is better explained with an example). (最好用一个例子来解释)。
Df1 (in my actual problem there are +1000 rows) Df1(在我的实际问题中有+1000行)
'Fert 1' 'Fert 2' 'Fert 3'
A 1000 900 800
B 100 90 80
C 10 9 8
D 0.1 0.9 0.8
Df2 (smaller df where the row names are the same as df1 column names) Df2(较小的 df,其中行名与 df1 列名相同)
'L1' 'L2'
'Fert 1' 1 0.5
'Fert 2' 2 0
'Fert 3' 1 0.5
Desired result: Basically I want df1 that has been multiplied by df2 and expanded (I want the column names to be multi-index).期望的结果:基本上我想要 df1 乘以 df2 并展开(我希望列名是多索引)。 I can do it with a nested loop although I can't get the correct column headers that way.我可以使用嵌套循环来做到这一点,尽管我无法以这种方式获得正确的列标题。 And looping seems like an inefficient way of doing it because it gets slow with my bigger dataset.并且循环似乎是一种低效的方式,因为它在我更大的数据集下变得很慢。 I am hoping it can be done using a merge or concat but I just can't work it out.我希望它可以使用合并或连接来完成,但我无法解决。
'Fert 1' 'Fert 2' 'Fert 3'
'L1' 'L2' 'L1' 'L2' 'L1' 'L2'
A 1000 500 1800 0 800 400
B 100 50 180 0 80 40
C 10 5 18 0 8 4
D 0.1 0.05 1.8 0 0.8 0.4
Thanks for any help!谢谢你的帮助!
Create MultiIndex
by DataFrame.stack
, repeat columns by DataFrame.reindex
so possible multiple by Series
with DataFrame.mul
:通过DataFrame.mul
创建MultiIndex
,通过DataFrame.stack
重复列,以便通过DataFrame.reindex
的Series
可能多个:
s = Df2.stack()
df = Df1.reindex(s.index, axis=1, level=0).mul(s)
print (df)
'Fert 1' 'Fert 2' 'Fert 3'
'L1' 'L2' 'L1' 'L2' 'L1' 'L2'
A 1000.0 500.00 1800.0 0.0 800.0 400.0
B 100.0 50.00 180.0 0.0 80.0 40.0
C 10.0 5.00 18.0 0.0 8.0 4.0
D 0.1 0.05 1.8 0.0 0.8 0.4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.