python - 在子数据帧上使用移动平均线?
问题描述
我有一个由数据框中的一组日期组成的子数据框。我想计算同一子数据框架内的移动平均值并将其绘制在我已经拥有的同一图表上(显示子框架中每天的案例数)。移动平均线需要从 3 月 7 日到 7 月 10 日,并且窗口需要 =7(一周)。
示例数据:
sex country date_report
M Canada 03-01-2020
F Canada 03-01-2020
M Canada 03-02-2020
F Canada 03-02-2020
M Canada 03-02-2020
M Canada 03-03-2020
F Canada 03-03-2020
M Canada 03-04-2020
F Canada 03-04-2020
M Canada 03-04-2020
我已经拥有的代码
day_first=datetime.date(2020, 3, 1)
day_last=datetime.date(2020, 7, 10)
delta = (day_last - day_first)
print(delta.days)
for i in range(delta.days + 1):
all_dates = day_first + datetime.timedelta(+i)
print(all_dates) # This gives me the range of dates I am looking for.
date_count=df.groupby('date_report').date_report.count()
sub_df = df.loc[df['date_report'].between(day_first,day_last), :]
date_count = sub_df.groupby('date_report').date_report.count()
ax=date_count.plot(kind='line')
ax.xaxis.set_major_locator(months)
plt.xlabel("March 1/2020 to July 10/2020")
plt.ylabel("Number of Cases")
plt.show()
这将创建一个如下所示的图:
我只需要计算同一子数据框中的每周移动平均值,然后将其绘制在同一图表上。提前感谢您的帮助,并对屏幕截图表示抱歉-我无法以其他方式添加图片,因为我是 stackoverflow 的新手!
解决方案
我认为您正在寻找使用rolling
,可用于创建移动平均线。这是一个尝试模仿您的示例,rolling
用于添加另一条曲线:
import pandas as pd
import numpy as np
#the range of dates you mention
dr = pd.date_range('3-7-2020','7-10-2020',freq='D')
#df with a date_report column which is 1000 randomly chosen dates from dr
df = pd.DataFrame(np.random.choice(dr, size=1000), columns=['date_report'])
#your groupby operation and plotting
counts = df.groupby('date_report').date_report.count()
counts.index = counts.index.date
ax = counts.plot(kind='line')
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
#now creating a rolling 7 day window and plotting
counts.index = pd.to_datetime(counts.index)
rolling = counts.rolling('7D').mean()
rolling.plot()
我进行了编辑以包含 x 轴的一些日期格式。可能有更好的方法,但你可以看到我做了一些烦人的日期转换counts
以使其工作(请参阅我的其他帖子)
推荐阅读
- c# - 托管在 Windows 服务中的 ASP.NET Core - 未提供静态文件(即 /wwwroot 的内容)
- java - 来自 mssql 数据库的快速流式批处理数据
- ios - 如何更改 Podfile 中的现有存储库 URL,将所有 pod 更新到新存储库
- python - Pygame 无法加载图像并且错误消息不显示相同的文件
- sql - SQL 按升序排序,但将 Null 视为最大值
- android - gradlew assembleRelease 它在 react-native 中给出以下错误
- internet-explorer - ASPSessionID 在 IE 11 上的请求之间间歇性更改
- infinispan - 在wildfly中注册infinispan缓存监听器
- javascript - 使用 AJAX 解析用于电子表格上传的 CSV 文件行
- biml - 是否可以从 BIML 中的 GetTableSql() 中删除列