【问题标题】:Resample time series data in dictionary with python用python重新采样字典中的时间序列数据
【发布时间】:2021-06-05 19:43:06
【问题描述】:

我有按以下格式存储在字典中的每日价格历史数据:

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)

但我想按月对我的数据进行重新采样。 我该怎么做?

【问题讨论】:

  • 下面我的回答解决了你的问题吗?如果是,请投票并标记为已接受的答案。如果没有,请告诉我您还需要什么,我会提供帮助。 :)

标签: python pandas dictionary time-series data-analysis


【解决方案1】:

这就是你所追求的吗?您可以将您的 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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多