Python Pandas SUMPRODUCT 和 L 矩阵计算

Python Pandas SUMPRODUCT and L Matrix caluclation

我必须使用 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)-SUMPRODUCT($B2:B,$A2:A),0)
C2=IFERROR($B3*SUM(A:$A3)-SUMPRODUCT($B:B3,$A:A3),0)
.....
....
C14=IFERROR($B14*SUM(A:$A14)-SUMPRODUCT($B:B14,$A:A14),0)

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

使用cumsum with multiple by 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