Home > Net >  Pandas: DataFrame Rolling Average on a Row
Pandas: DataFrame Rolling Average on a Row

Time:01-24

I have a Row of values in a dataframe and want to calculate the rolling average (3 Period) by creating a new row.

existing_row                1 2 3 4 5 6 7 8 9 


create_new_row                  2 3 4 5 6 7 8

CodePudding user response:

Use DataFrame.rolling with axis=1 and mean:

print (df)
   0  1  2  3  4  5  6  7  8
0  1  2  3  4  5  6  7  8  9

df1 = df.rolling(3, axis=1).mean()
print (df1)
    0   1    2    3    4    5    6    7    8
0 NaN NaN  2.0  3.0  4.0  5.0  6.0  7.0  8.0

If need join to original pass to concat:

df = pd.concat([df, df1], ignore_index=True)
print (df)
     0    1    2    3    4    5    6    7    8
0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
1  NaN  NaN  2.0  3.0  4.0  5.0  6.0  7.0  8.0

CodePudding user response:

Use rolling_mean:

out = df.append(df.rolling(3, axis=1).mean(), ignore_index=True)
print(out)

# Output
     A    B    C    D    E    F    G    H    I
0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0
1  NaN  NaN  2.0  3.0  4.0  5.0  6.0  7.0  8.0

Setup:

df = pd.DataFrame({'A': {0: 1}, 'B': {0: 2}, 'C': {0: 3}, 'D': {0: 4}, 'E': {0: 5}, 
                   'F': {0: 6}, 'G': {0: 7}, 'H': {0: 8}, 'I': {0: 9}})
print(df)

# Output
   A  B  C  D  E  F  G  H  I
0  1  2  3  4  5  6  7  8  9
  •  Tags:  
  • Related