AMM*_*AMM 5 python mean moving-average pandas
我如何计算滚动平均值或移动平均值,其中我考虑了迄今为止我看到的所有项目。
假设我有一个如下所示的数据框
col new_col
0 1 1
1 2 1.5
2 3 2
Run Code Online (Sandbox Code Playgroud)
等等。现在我想添加一个新列,在那里我计算 col 中所有项目的平均值,直到该点。指定一个窗口意味着我将获得前几个作为 Nan ,然后它只做一个滚动窗口。但我需要类似上面的东西。
下面的代码片段将完全满足您的要求。但还有很大的改进空间。它使用带有 if-else 语句的 for 循环。使用向量化函数肯定有更快的方法来做到这一点。如果您省略该部分,它还会触发SettingsWithCopyWarningpd.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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2036 次 |
| 最近记录: |