使用熊猫计算简单的历史平均值

时间:2021-05-11 02:06:43

标签: python pandas dataframe numpy time-series

我有一个如下所示的数据框

data = pd.DataFrame({'day':['1','21','41','61','81','101','121','141','161','181','201','221'],'Sale':[1.08,0.9,0.72,0.58,0.48,0.42,0.37,0.33,0.26,0.24,0.22,0.11]})

我想通过计算直到 day 241 的所有记录的平均值来填充 day 221 的值。同样,我想通过计算 day 261 之前所有记录的平均值来计算 day 241 的值,依此类推。

例如:通过取 day n 中所有值的平均值来计算 day 1 to day n-21 的值。

我想这样做直到 day 1001

我尝试了以下但不正确

df['day'] = df.iloc[:,1].rolling(window=all).mean()

如何在 day 列下为每一天创建新行?

我希望我的输出如下所示

enter image description here

1 个答案:

答案 0 :(得分:5)

听起来您正在寻找扩大均值:

import numpy as np
import pandas as pd

df = pd.DataFrame({'day': ['1', '21', '41', '61', '81', '101', '121', '141',
                           '161', '181', '201', '221'],
                   'Sale': [1.08, 0.9, 0.72, 0.58, 0.48, 0.42, 0.37, 0.33, 0.26,
                            0.24, 0.22, 0.11]})

# Generate Some new values
to_add = pd.DataFrame({'day': np.arange(241, 301, 20)})

# Add New Values To End of DataFrame
new_df = pd.concat((df, to_add)).reset_index(drop=True)

# Replace Values Where Sale is NaN with the expanding mean
new_df['Sale'] = np.where(new_df['Sale'].isna(),
                          new_df['Sale'].expanding().mean(),
                          new_df['Sale'])
print(new_df)
    day      Sale
0     1  1.080000
1    21  0.900000
2    41  0.720000
3    61  0.580000
4    81  0.480000
5   101  0.420000
6   121  0.370000
7   141  0.330000
8   161  0.260000
9   181  0.240000
10  201  0.220000
11  221  0.110000
12  241  0.475833
13  261  0.475833
14  281  0.475833

将 NaN 替换为 1 然后求平均值:

import numpy as np
import pandas as pd

df = pd.DataFrame({'day': ['1', '21', '41', '61', '81', '101', '121', '141',
                           '161', '181', '201', '221'],
                   'Sale': [1.08, 0.9, 0.72, 0.58, 0.48, 0.42, 0.37, 0.33, 0.26,
                            0.24, 0.22, 0.11 ]})

# Generate Some new values
to_add = pd.DataFrame({'day': np.arange(241, 301, 20)})

# Add New Values To End of DataFrame
new_df = pd.concat((df, to_add)).reset_index(drop=True)
# Replace Values Where Sale is NaN with the expanding mean
new_df['Sale'] = np.where(new_df['Sale'].isna(),
                          new_df['Sale'].fillna(1).shift().expanding().mean(),
                          new_df['Sale'])
print(new_df)
    day      Sale
0     1  1.080000
1    21  0.900000
2    41  0.720000
3    61  0.580000
4    81  0.480000
5   101  0.420000
6   121  0.370000
7   141  0.330000
8   161  0.260000
9   181  0.240000
10  201  0.220000
11  221  0.110000
12  241  0.475833
13  261  0.516154
14  281  0.550714