在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

输出数据框:

     a   b   d
A   10  20  30
B   60  80 100
C  150 180 210

调用axis=0,通过转换为列表,我们将忽略索引/列名称的所有对齐错误:>

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

编辑

无需转换为列表,只需直接访问系列:

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