问题
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,200]}
df=pd.DataFrame(d)
A
0 100
1 110
2 120
3 175
4 164
5 169
6 155
7 153
8 156
9 200
0 NaN
1 NaN
2 330.0 #this is the result tho
3 405.0
4 459.0
5 508.0
6 488.0
7 477.0
8 464.0
9 509.0
Name: sum, dtype: float64
And i want to display the equation process like this:
NaN
NaN
330.0 = 100+110+120
405.0 = 110+120+175
459.0 .
508.0 .
488.0 .
477.0 .
464.0 .
509.0 etc.
Here's the code that i tried with for loop:
for i in range(len(total)):
print("{}={}+{}+{}".format(total[i],"a","b","c"))
nan=a+b+c
nan=a+b+c
330.0=a+b+c
405.0=a+b+c
459.0=a+b+c
508.0=a+b+c
488.0=a+b+c
477.0=a+b+c
464.0=a+b+c
509.0=a+b+c
PS: a
, b
, and c
replaced with the number from the dataframe
I don't know if it possible with pandas library or just do it with python library only. I'm just curious
回答1:
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]))
回答2:
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
来源:https://stackoverflow.com/questions/64089678/how-to-print-rolling-window-equation-process-from-pandas-dataframe-in-python