首页 > 解决方案 > Python Pandas 函数计算前一行和当前行

问题描述

'Excel 工作表示例'

给一个我想转换为另一个的 DataFrame,其中转换函数对前一行和当前行进行操作。在给定的示例中,

RowID =1 is copied as is,

但从 RowID 2 开始,

Current Cell = Max(CurrentCell, Previous Cell * 0.9999 )
H4 <= MAX(B4, H3*0.9999)
where,
B4  = original value, 
H3  = the previous row **'After Transformation'**

在此处输入图像描述

标签: pythonpandas

解决方案


这是在路上,用cumsumand创建你自己的函数cumcount,然后update是列

def yourfun(s):
    s.update(s.mask(s==0).ffill()-s.groupby(s.mask(s==0).eq(1).cumsum()).cumcount()*0.0001)
    return s
df.apply(yourfun)
Out[291]: 
        1       2       3       4
0  0.0000  0.0000  1.0000  0.0000
1  0.0000  1.0000  0.9999  1.0000
2  0.0000  0.9999  0.9998  0.9999
3  1.0000  0.9998  0.9997  1.0000
4  0.9999  1.0000  1.0000  0.9999
5  0.9998  0.9999  0.9999  0.9998
6  1.0000  0.9998  0.9998  0.9997

推荐阅读