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

后端 未结 2 958
眼角桃花
眼角桃花 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
    
    0 讨论(0)
  • 2021-01-23 21:06
    d={'A':[100,110,120,175,164,169,155,153,156,200]}
    df=pd.DataFrame(d)
    for ind in df.index:
            if ind == 0 or ind == 1:
                print("NaN")
            else:
                sumOf3Numbers = df["A"][ind-2]+df["A"][ind-1]+df["A"][ind]
                print("{}={}+{}+{}".format(sumOf3Numbers,df["A"][ind-2],df["A"][ind-1],df["A"][ind]))
    
    0 讨论(0)
提交回复
热议问题