lena242
lena242

Reputation: 55

Elementwise multiplication of pandas Dataframes with different indices

I have two pandas dataframes:

df1=pd.DataFrame({'month':['jun', 'jul', 'aug'],'a':[3,4,5], 'b':[2,3,4], 'c':[4,5,5]}).set_index('month')

       a  b  c
month         
jun    3  2  4
jul    4  3  5
aug    5  4  5

and

df2=pd.DataFrame({'year':[2009,2009,2009, 2010,2010,2010,2011,2011,2011],'month':['jun', 'jul', 'aug','jun', 'jul', 'aug','jun', 'jul', 'aug'],'a':[2,2,2,2,2,2,2,2,2], 'b':[1,2,3,4,5,6,7,8,9], 'c':[3,3,3,3,3,3,3,3,3]}).set_index('year')

     month  a  b  c
year               
2009   jun  2  1  3
2009   jul  2  2  3
2009   aug  2  3  3
2010   jun  2  4  3
2010   jul  2  5  3
2010   aug  2  6  3
2011   jun  2  7  3
2011   jul  2  8  3
2011   aug  2  9  3

I would like to multiply df2's elements with df1's according to the months. Is there quick way to do it?

Thanks in adavance.

Upvotes: 1

Views: 226

Answers (1)

jezrael
jezrael

Reputation: 863781

Use DataFrame.mul by months converted to MultiIndex by DataFrame.set_index :

df = df2.set_index('month', append=True).mul(df1, level=1).reset_index(level=1)
print (df)
     month   a   b   c
year                  
2009   jun   6   2  12
2009   jul   8   6  15
2009   aug  10  12  15
2010   jun   6   8  12
2010   jul   8  15  15
2010   aug  10  24  15
2011   jun   6  14  12
2011   jul   8  24  15
2011   aug  10  36  15

Upvotes: 2

Related Questions