Python Pandas SUMPRODUCT 和 L 矩阵计算

标签 python excel pandas numpy-einsum

我必须采用 pandas 数据帧格式的列,并希望 C D 列中的输出如下

 A   B   C             D
 1   2   1*2           1*2
 3   4   (1+3)*4       (1*2)+(3*4)
 5   6   (1+3+5)*6     (1*2)+(3*4)+(5*6)
 7   8   (1+3+5+7)*8   (1*2)+(3*4)+(5*6)+(7*8)
 9   10  ....          .....

这里我试图用Python方式编写Excel公式,有人可以为此抛出代码

a) python code for top to bottom calculation
Excel Formulas for the final outcome:
C1=IFERROR($B2*SUM(A2:$A$2)-SUMPRODUCT($B2:B$2,$A2:A$2),0)
C2=IFERROR($B3*SUM(A$2:$A3)-SUMPRODUCT($B$2:B3,$A$2:A3),0)
.....
....
C14=IFERROR($B14*SUM(A$2:$A14)-SUMPRODUCT($B$2:B14,$A$2:A14),0)

b) python code for bottom to top calculation from bottom
e1==IFERROR(SUMPRODUCT($B2:B$14,$C2:C$14)-$B2*SUM($C2:C$14),0)
E2=IFERROR(SUMPRODUCT($B3:B$14,$C3:C$14)-$B3*SUM($C3:C$14),0)
e4=IFERROR(SUMPRODUCT($B4:B$14,$C4:C$14)-$B4*SUM($C4:C$14),0)
.....
.....
.....
e14=IFERROR(SUMPRODUCT($B14:B$14,$C14:C$14)-$B14*SUM($C14:C$14),0)

最佳答案

使用cumsum乘以 mul 的倍数:

df['C'] = df['A'].cumsum().mul(df['B'])
df['D'] = df[['A', 'B']].prod(1).cumsum()

或者:

df = df.assign(C=df['A'].cumsum().mul(df['B']),
               D=df['A'].mul(df['B']).cumsum())

print (df)
   A   B    C    D
0  1   2    2    2
1  3   4   16   14
2  5   6   54   44
3  7   8  128  100
4  9  10  250  190

编辑:

对于反向值,最简单的是使用iloc[::-1]:

df = df.assign(C=df['A'].iloc[::-1].cumsum().mul(df['B']),
               D=df[['A', 'B']].iloc[::-1].prod(1).cumsum())

print (df)
   A   B    C    D
0  1   2   50  190
1  3   4   96  188
2  5   6  126  176
3  7   8  128  146
4  9  10   90   90

编辑1:

df = pd.DataFrame({'A':[1,3,5,7,9], 'B':[2,4,6,8,10]})
df['C']=df['A'].iloc[::-1].cumsum().mul(df['B'])
df['D']=df[['A', 'B']].iloc[::-1].prod(1).cumsum()

print (df)
   A   B    C    D
0  1   2   50  190
1  3   4   96  188
2  5   6  126  176
3  7   8  128  146
4  9  10   90   90

#create index by column A
x = df.set_index('A')
print (x)
    B    C    D
A              
1   2   50  190
3   4   96  188
5   6  126  176
7   8  128  146
9  10   90   90

#get index of minimal value by D column
print (x['D'].idxmin())
9

关于Python Pandas SUMPRODUCT 和 L 矩阵计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48074166/

相关文章:

python - web2py 中组合键的最佳实践

python - 转置 Pandas 中具有公共(public)行值的行

javascript - 在 Django 中使用 SIMPLE javascript 确认删除

Python - 在 CSV 之间复制列,但组合字符串/整数值复制为空白?

python - 在 Python Matplotlib 中创建子图

excel - 将使用的范围复制到文本文件

excel - 将维度与非重叠数据相结合 (Tableau)

Excel 上的 VBA 应用程序

python - 在列表中的 pandas 列中查找关键字匹配项的数量

python-3.x - Pandas 数据透视表从索引的 0 级切片