将两个具有相同形状和相同列名的 Pandas 数据框相乘

imp*_*ble 5 python dataframe pandas

我有两个 NxM 形状的数据框 A、B。我想将两者相乘,使 A 的每个元素与 B 的各个元素相乘。

e.g:
A,B = input dataframes
C = final dataframe
I want C[i][j] = A[i][j]*B[i][j] for i=1..N and j=1..M
Run Code Online (Sandbox Code Playgroud)

我搜索但无法得到确切的解决方案。

jez*_*ael 5

我认为你可以使用:

C = A * B
Run Code Online (Sandbox Code Playgroud)

下一个解决方案是mul

C = A.mul(B)
Run Code Online (Sandbox Code Playgroud)

样本:

print A
   a  b
0  1  3
1  2  4
2  3  7

print B
   a  b
0  2  3
1  1  4
2  3  2

print A * B
   a   b
0  2   9
1  2  16
2  9  14

print A.mul(B)
   a   b
0  2   9
1  2  16
2  9  14
Run Code Online (Sandbox Code Playgroud)

计时用的lenghtAB 300K

In [218]: %timeit A * B
The slowest run took 4.27 times longer than the fastest. This could mean that an intermediate result is being cached 
100 loops, best of 3: 3.57 ms per loop

In [219]: %timeit A.mul(B)
100 loops, best of 3: 3.56 ms per loop

A = pd.concat([A]*100000).reset_index(drop=True)
B = pd.concat([B]*100000).reset_index(drop=True)

print A * B
print A.mul(B)
Run Code Online (Sandbox Code Playgroud)