我有两个数据框 A、B,形状为 NxM。我想将两者相乘,使得 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
我进行了搜索,但无法找到确切的解决方案。
最佳答案
我认为你可以使用:
C = A * B
下一个解决方案是 mul
:
C = A.mul(B)
示例:
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
Timings,长度为 A
和 B
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)
关于python - 将两个具有相同形状和相同列名的 Pandas 数据框相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530293/