I have two dataframes shown below; I want to multiply each column of df1 with each value in the corresponding row in df2. Each time should produce a new column. (It is better explained with an example).
Df1 (in my actual problem there are +1000 rows)
'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)
'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). 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
:
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
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.