首页 > 解决方案 > 用python重新采样字典中的时间序列数据

问题描述

我将每日价格历史数据以下列格式存储在字典中:

test = 
{
datetime(2020, 1, 15): 15.99,
datetime(2020, 1, 16): 18.99,
datetime(2020, 1, 17): 20.99,
datetime(2020, 1, 18): 14.99
.......
}

我可以用以下方法绘制这些数据:

x = list(test.keys())
y = list(test.values())
plt.plot(x,y)

但我想将我的数据重新采样为每月一次。我怎样才能做到这一点?

标签: pythonpandasdictionarytime-seriesdata-analysis

解决方案


这就是你所追求的吗?您可以将您的 dict 转换为具有日期时间索引的 df,然后以这种方式重新采样,按总和进行聚合。不得不使用 datetime.datetime() 而不仅仅是你的例子中的 datetime() 。

test = {
datetime.datetime(2020, 1, 15): 15.99,
datetime.datetime(2020, 1, 16): 18.99,
datetime.datetime(2020, 1, 17): 20.99,
datetime.datetime(2020, 1, 18): 14.99,
datetime.datetime(2020, 2, 18): 17.99,
datetime.datetime(2020, 2, 19): 21.99

}

# make a df and transpose it with .T
df = pd.DataFrame(test, index=[0]).T

# rename column 0 so it's more descriptive
df.columns = ['monthly_price_sum']

# resample and choose to aggregate values by sum, but could use max, min, mean, etc.
df = df.resample('M').sum()

print(df)


            monthly_price_sum
2020-01-31  70.96
2020-02-29  39.98

如果你想回到一个字典,你可以这样做。Zip 很好地避免了在 new_dict 中的多余嵌套。

new_dict = dict(zip(df.index, df['monthly_price_sum]))

print(new_dict)

{Timestamp('2020-01-31 00:00:00', freq='M'): 70.96, Timestamp('2020-02-29 00:00:00', freq='M'): 39.98}

您可以像这样绘制输出。

df.plot(xlabel='month', ylabel='monthly price sum')

在此处输入图像描述


推荐阅读