Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply two data frames with similar index in python pandas

I have two data frames and I want to multiply them by index. What the best way to do this? NOTE: Column names are different.

df1 = pd.DataFrame([(1,2,3),(3,4,5),(5,6,7)], columns=['a','b','d'], index = ['A', 'B','C'])
df1
   a  b  d
A  1  2  3
B  3  4  5
C  5  6  7

df2 = pd.DataFrame([(10,20,30)], columns=['A','B','C'],index = ['ss'])
df2 = df2.transpose()
df2
   ss
A  10
B  20
C  30

Output Dataframe:

     a   b   d
A   10  20  30
B   60  80 100
C  150 180 210
like image 937
cryp Avatar asked Apr 08 '26 08:04

cryp


2 Answers

Call mul and convert the Series to a list and pass axis=0, by converting to a list we ignore any alignment errors with the index/column names:

In [74]:

df1.mul(list(df2['ss']), axis=0)
Out[74]:
     a    b    d
A   10   20   30
B   60   80  100
C  150  180  210

EDIT

No need to convert to a list just access the Series directly:

In [75]:

df1.mul(df2['ss'], axis=0)
Out[75]:
     a    b    d
A   10   20   30
B   60   80  100
C  150  180  210
like image 173
EdChum Avatar answered Apr 10 '26 22:04

EdChum


One way could be to multiply on Numpy arrays like

In [8]: pd.DataFrame(df1.values*df2.values,
                      columns=['a','b','d'], index = ['A', 'B','C'])
Out[8]:
     a    b    d
A   10   20   30
B   60   80  100
C  150  180  210
like image 40
Zero Avatar answered Apr 10 '26 21:04

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!