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

标签 python pandas dataframe

我有两个数据框 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,长度为 AB 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/

相关文章:

python - 如何使用 pandas 将 Datetime 对象聚合为 int

python - 使用多列连接 Pandas 数据框

r - 将R中选定列中的所有NA替换为FALSE

python - pivot_table 索引中的 NaN 值导致数据丢失

python - 奇怪的多处理 block 导入 Numba 函数

python - 在 PySimpleGUI 中浏览文件或文件夹

pandas - DataFrame图上日期的x轴标签频率增加

python - Groupby 中的项目计数

python - 从 python 或 shell 脚本更改工作目录

Python CGI 返回一个 http 状态代码,例如 403?