How to print rolling window equation process from pandas dataframe in python?

后端 未结 2 961
眼角桃花
眼角桃花 2021-01-23 20:26

I created a pandas dataframe sample and it tried to sum for every 3 rows:

import pandas as pd
import numpy as np

d={\'A\':[100,110,120,175,164,169,155,153,156,20         


        
2条回答
  •  广开言路
    2021-01-23 21:05

    It's a little bit tricky to get rolling to work with conditional string output

    equations = []
    df.A.rolling(3).apply(lambda x: equations.append(f'{x.sum()} = {x.iloc[0]}+{x.iloc[1]}+{x.iloc[2]}') or 0)
    df.loc[2:, 'equations'] = equations
    print(df)
    

    Out:

         A                  equations
    0  100                        NaN
    1  110                        NaN
    2  120  330.0 = 100.0+110.0+120.0
    3  175  405.0 = 110.0+120.0+175.0
    4  164  459.0 = 120.0+175.0+164.0
    5  169  508.0 = 175.0+164.0+169.0
    6  155  488.0 = 164.0+169.0+155.0
    7  153  477.0 = 169.0+155.0+153.0
    8  156  464.0 = 155.0+153.0+156.0
    9  200  509.0 = 153.0+156.0+200.0
    

提交回复
热议问题