【问题标题】:plot average value every 30 minutes每 30 分钟绘制一次平均值
【发布时间】:2021-06-16 13:06:20
【问题描述】:

我正在尝试每 30 分钟绘制一次“传播”的平均值。我的数据是这样的

                        Bid      Ask    Spread     relative_spread       relative_quoted_half_spread
Date
2021-02-01 00:01:02  1.21291  1.21336  0.00045         0.000371                     0.000185
2021-02-01 00:01:21  1.21290  1.21336  0.00046         0.000379                     0.000190
2021-02-01 00:01:31  1.21287  1.21336  0.00049         0.000404                     0.000202
2021-02-01 00:01:32  1.21290  1.21336  0.00046         0.000379                     0.000190
2021-02-01 00:02:08  1.21290  1.21338  0.00048         0.000396                     0.000198

我的第一次尝试是

plt.figure('Average spread over time')
minutes_dfs = df.resample('30M').mean()
print(Date)

ax3 = minutes_dfs.plot(x='Date', y='Spread',ls='-',color='k')
ax3.set_title('Spread introday every 30mins')
ax3.set_ylabel('Spread change')
ax3.legend(loc='best')
ax3.grid(True)
plt.show()

我收到一条错误消息“发生异常:KeyError 'Date'” 但是,我在绘制之前已经尝试过了

print(Date)

我得到了这样的日期列结果

0       2021-02-01 00:01:02
1       2021-02-01 00:01:21
2       2021-02-01 00:01:31
3       2021-02-01 00:01:32
4       2021-02-01 00:02:08

我的第二次尝试是

plt.figure('Average spread over time')
minutes_dfs = df.groupby(pd.Grouper(key = 'Date', freq='30M')).mean()
print(Date)

ax3 = minutes_dfs.plot(x='Date', y='Spread',ls='-',color='k')
ax3.set_title('Spread introday every 30mins')
ax3.set_ylabel('Spread change')
ax3.legend(loc='best')
ax3.grid(True)
plt.show()

然后我收到这样的错误消息 '未找到石斑鱼名称日期'

有谁知道我哪里出错了? 提前致谢!

【问题讨论】:

    标签: python pandas date datetime plot


    【解决方案1】:

    因为Date是索引需要删除x

    x3 = minutes_dfs.plot(y='Spread',ls='-',color='k')
    

    或添加reset_index:

    x3 = minutes_dfs.reset_index().plot(x='Date', y='Spread',ls='-',color='k')
    

    在第二个解决方案中去掉key参数,因为DatetimeIndex:

    minutes_dfs = df.groupby(pd.Grouper(freq='30M')).mean()
    
    x3 = minutes_dfs.plot(y='Spread',ls='-',color='k')
    

    【讨论】:

    • 感谢您的回答。我已经尝试了这两种解决方案,但是,通过删除“日期”,x 轴从 2019 年开始到 2023 年。我的数据只有一天的数据。
    • @jezrael 是的,我也试过了 ** df = df.set_index('Date') # Set index as Date** 设置索引。
    • @Susie - 所以你的问题在于数据是从20192023 的日期时间并且正在绘制?不明白。
    • 很抱歉给您带来了困惑。是的,应该不是从2019年到2023年。我也试过print (ax3.index)得到错误信息'AxesSubplot' object has no attribute 'index'
    • @Susie - 如果没有从20192023 的数据,需要什么?问题是需要过滤数据吗?因为在你的档案里有很多年?
    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多