Moving average or average pandas rolling without any window size

How to calculate a moving average or moving average, where I consider all the elements that I have seen so far.

Say I have a data frame as shown below

   col   new_col
0    1      1
1    2      1.5
2    3      2

etc. Now I would like to add a new column, where I drop the average of all the elements in the column to this point. Setting the window will mean that I will get the first few, like Nan, and then it will only be a pivot window. But I need something like the above.

+4
source share
1 answer

, . . for if-else. , . SettingsWithCopyWarning, pd.options.mode.chained_assignment = None.

:

# Libraries
import pandas as pd
import numpy as np

# Settings
pd.options.mode.chained_assignment = None

# Dataframe with desired input
df = pd.DataFrame({'col':[1,2,3]})

# Make room for a new column
df['new_col'] = np.nan

# Fill the new column with values
for i in df.index + 1:
    if i == 0:
        df['new_col'].iloc[i] = np.nan
    else:
        df['new_col'].iloc[i-1] = pd.rolling_mean(df.col.iloc[:i].values, window = i)[-1]
print(df)

:

enter image description here

0

Source: https://habr.com/ru/post/1540989/


All Articles