python - 计算简单的移动平均熊猫循环
问题描述
我目前正在尝试计算几只股票数据集的简单移动平均线。为了简单起见,我只在两家公司(和 4 天的时间)上尝试了代码以使其正常工作,但输出似乎存在一些问题。下面是我的代码。
for index, row in df3.iloc[4:].iterrows():
if df3.loc[index,'CompanyId'] == df3.loc[index-4,'CompanyId']:
df3['SMA4'] = df3.iloc[:,1].rolling(window=4).mean()
else:
df3['SMA4'] = 0
这是输出:输出
数据框按日期和公司 ID 排序。所以需要发生的是,当公司 id 不等于代码中所述时,输出应该为零,因为我无法计算两家不同公司的移动平均值。相反,它会输出两家公司的移动平均线,如第 7、8、9 行。
解决方案
利用groupby.rolling
df['SMA4']=df.groupby('CompanyId',sort=False).rolling(window=4).Price.mean().reset_index(drop='CompanyId')
print(df)
CompanyId Price SMA4
0 1 75 NaN
1 1 74 NaN
2 1 77 NaN
3 1 78 76.00
4 1 80 77.25
5 1 79 78.50
6 1 80 79.25
7 0 10 NaN
8 0 9 NaN
9 0 12 NaN
10 0 11 10.50
11 0 11 10.75
12 0 8 10.50
13 0 9 9.75
14 0 8 9.00
15 0 8 8.25
16 0 11 9.00
推荐阅读
- php - php - Mysql Query 工作除了一个过滤器
- c# - 关于加速硬盘备份代码的建议
- java - 在 Java 中 String hashCode() 的旧 impl 中跳过字符背后的想法是什么
- python - 如何运行托管在 a2hosting 上的 Flask 应用程序?
- matlab - 如何优化此字符串替换代码
- angular7 - 两种语言 Angular 构建,一种正常,一种有错误
- c# - C# - 线程任务 - Dotnet 4.x 中的最佳实践
- nix - 如何将我的 nix 环境重置为原始用户配置文件?
- c# - MailAddress 到正确的传真服务器工作不正常
- reactjs - 如何在reactjs的组件中使用存储在另一个constant.js文件中的数组