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
解决方案
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