作为我正在学习的课程的一部分,我需要计算火箭发射的每月累计总和,并计算月到月的滚动平均值,最后在一个图上显示这两个结果。
dataframe包含Date、Launch site、Mission status和其他一些不太重要的参数。日期格式为YYYY-MM-DD,每个不同的年-月组合的项目数不同.
输入数据如下所示:
Organisation Location Date Detail Rocket_Status Price Mission_Status
4323 RVSN USSR Site 1/5, Baikonur Cosmodrome, Kazakhstan 1957-10-04 19:28:00+00:00 Sputnik 8K71PS | Sputnik-1 StatusRetired 63.23 Success
4322 RVSN USSR Site 1/5, Baikonur Cosmodrome, Kazakhstan 1957-11-03 02:30:00+00:00 Sputnik 8K71PS | Sputnik-2 StatusRetired 63.23 Success
4321 US Navy LC-18A, Cape Canaveral AFS, Florida, USA 1957-12-06 16:44:00+00:00 Vanguard | Vanguard TV3 StatusRetired 63.23 Failure我的方法是:
函数创建单独的df:
launchdays = pd.DataFrame(spacerace.groupby(spacerace.loc[:,"Date"].dt.date).agg("size"))此数据包含以下数据:
0
Date
1957-10-04 1
1957-11-03 1
1957-12-06 1
1958-02-01 1
1958-02-05 1将DateTimeIndex的
launchdays.index = pd.to_datetime(launchdays.index)monthly_data = launchdays.resample("M").sum()
rolling = launchdays.rolling(30).mean().dropna()重采样后的每月数据:
0
Date
1957-10-31 1
1957-11-30 1
1957-12-31 1
1958-01-31 0
1958-02-28 2滚动平均数:
0
Date
1958-12-18 1.03
1959-01-02 1.03
1959-02-17 1.03
1959-02-28 1.03
1959-04-13 1.03这似乎是可行的,至少在我看来,结果是现实的--然而,我想确定我的方法是否正确和/或是否可以更优雅地完成。
谢谢!
另一个编辑:
我已修正了收集每月数据和计算滚动平均数的部分:
monthly_data = launchdays.resample("30D").sum()
rolling = monthly_data.rolling(“30D").mean()然而,它们现在的产量完全相同,这是预料中的.也许我误解了这个练习中的一些东西?这一任务的定义是:“按月计算到现在的发射次数。哪个月的发射次数是有史以来最高的?在月时间序列图上加上一个滚动平均值。”
发布于 2022-02-27 12:24:06
我不知道我是否理解你的实际问题,我不喜欢辩论优雅和不雅的解决方案。如果他们工作,他们是好的。如果另一种解决方案更好,则取决于将不同的解决方案与同一问题进行比较的方式,例如,需要更少的时间、更少的内存或更少的代码行等等。
回到你的问题上,滚动平均值和重采样的总和是有区别的。滚动平均值是一种平滑数据的方法,以给出正确的趋势,参见https://en.wikipedia.org/wiki/Moving_average。相反,重采样和和方法是对被绑定数据的数据聚合,基本上是直方图https://en.wikipedia.org/wiki/Histogram。
因此,如果问题是哪个月的发射次数最多,则需要计算直方图并找到最大值。
在您的练习中滚动平均部分没有很好的定义,因为它没有给出窗口大小,或者至少给出了您应该平滑数据的更多信息。当然应该超过30天,因为有几个月多30天。我想这意味着一年(12个月)的窗口,但这纯粹是猜测。
编辑:我想他们的意思是这样的:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
np.random.seed(7)
pd.plotting.register_matplotlib_converters()
# create dummy data
dates = (
pd.Timestamp('1970-01-01') +
pd.to_timedelta(np.random.randint(0, 19000, 20000), unit='D')
)
success = np.random.random(len(dates)) > 0.05
df = pd.DataFrame({
'date': dates,
'success': success
})
df.sort_values('date', inplace=True)
df.reset_index(drop=True, inplace=True)
# create histogram
monthly = df['date'].groupby(
df['date'].dt.to_period('M').dt.to_timestamp()
).count()
print(monthly.loc[monthly==monthly.max()])
# add zeros for months that do not appear in the original histogram
monthly_dense = monthly.resample('MS').sum()
# plot
fig, ax = plt.subplots()
ax.plot(monthly_dense.index, monthly_dense)
ax.plot(monthly_dense.index, monthly_dense.rolling(12).mean())
fig.autofmt_xdate()https://stackoverflow.com/questions/71280885
复制相似问题