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
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!