按日期突出显示python图中的最大点

时间:2018-07-09 09:35:11

标签: python pandas matplotlib attributes

我知道这个问题确实与许多其他已回答的问题很接近,但是以前的所有答案都给了我同样的追溯问题。

我有一个简单的时间序列,我试图突出显示最高点。 我在处理“熊猫数据框”以获得在图上绘制的最大y值时遇到问题。我想我快要在那里了,但我认为pd.read_csv导入的parse_dates参数弄乱了我的索引编制。

当导入数据集时,我有一个datetime列和一个wind_speed列。当我对每日平均值进行重新采样时,变量列的标题消失,而datetime列变得无法调用。

在获取每日平均值之前:

In[12]: weather.head()
Out[12]:                                  wind_speed
            d_stamp_t_stamp                
            2017-07-26 00:05:09        1.31
            2017-07-26 00:35:13        1.62
            2017-07-26 01:05:05        1.50
        .......

采用每日平均值后:

wind_avg = weather.wind_speed.resample('D').mean()

d_stamp_t_stamp
2017-09-01    3.870625
2017-09-02    4.386875
2017-09-03    5.426739
2017-09-04    2.718750
2017-09-05    3.407708

wind_speed列的标签消失了,我似乎无法再对该数据进行采样了。

这是到目前为止的时间序列代码:

## Import weather data.
weather = pd.read_csv('/Users/regina/university_projects/Themo_Data/Weather0717-0618.csv', 
                 parse_dates=[[0,1]], index_col=0)
wind_avg = weather.wind_speed.resample('D').mean()

## Wind Speed graph
windplot = wind_avg.plot(title="Wind Speed", figsize=(12,8), 
                        fontsize=12, marker='o', markersize=7)
windplot.set_xlabel("Date"),windplot.set_ylabel("Wind Speed in m/s")

哪个给了我这张图表,y轴上的平均风速为。 enter image description here

当我尝试注释最大风速时,问题就来了。

y0 = max(wind_avg.wind_speed)
xpos = wind_avg.wind_speed.index(y0)
x0 = (wind_avg.d_stamp_t_stamp[xpos])

    windplot.annotate(
                "Max Speed", xy=(x0,y0), ha='right',
                va='bottom', textcoords='offset points', bbox=dict(BoxStyle='Round, pad=0.5', fc='yellow',
                alpha=0.5), arrowprops=dict(facecolor='black', shrink=0.05))

我收到这样的属性错误消息:

Traceback (most recent call last):

  File "<ipython-input-15-5e45876c5ebc>", line 5, in <module>
    y0 = max(wind_avg.wind_speed)

  File "/Users/regina/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 4372, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'Series' object has no attribute 'wind_speed'

关于重采样wind_speed列以删除其标签的方式是否存在某些问题?非常感谢大家!

1 个答案:

答案 0 :(得分:1)

在线

wind_avg = weather.wind_speed.resample('D').mean()

您将resample应用于数据框wind_speed列中的单个Pandas系列,因此您将获得一个Series作为返回值:

type(wind_avg)
Out: pandas.core.series.Series

尝试

weather_avg = weather.resample('D').mean()
type(weather_avg)
Out: pandas.core.frame.DataFrame

,您将获得每天对整个天气数据集的重新采样。

相关问题