python-熊猫数据帧的同一行但不同列中的单元格相乘之和

我有一个数据框

df = pd.DataFrame({'A':[1,2,3],'B':[2,3,4]})

我的数据看起来像这样

Index   A   B
0       1   2
1       2   3
2       3   4

我想计算每一行中A和B之间的乘法和.
预期结果应为(1×2)(2×3)(3×4)= 2 6 12 = 20.
我可以知道执行此操作而不是循环的pythonic方法吗?

解决方法:

您可以尝试多个列A和B,然后使用sum

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[1,2,3],'B':[2,3,4]})
print df
   A  B
0  1  2
1  2  3
2  3  4

print df['A'] * df['B']
0     2
1     6
2    12
dtype: int64

print (df['A'] * df['B']).sum()
20

或对所有所有列使用prod

print df.prod(axis=1)
0     2
1     6
2    12
dtype: int64

print df.prod(axis=1).sum()
20

谢谢ajcr评论

If you have just two columns, you can also use df.A.dot(df.B) for extra speed, but for three or more columns this is the way to do it!

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...