Indexing and slicing

Time series in Pandas can be indexed and sliced in many different ways, but it cannot be with integer indexes. Our index is dates, remember? Thus, to get all the data within the year 1988, we simply index with that year as a string. In the following code, we index it with the year 1988 and then plot the values:

temp['1988'].plot(lw=1.5) 
despine(plt.gca()) 
plt.gcf().autofmt_xdate() 
plt.minorticks_off() 
plt.ylabel('Temperature'), 

Indexing and slicing

The plot shows how the temperature varied over the year 1988, going from almost -30 to roughly +25 and then back to below zero around late October. As you probably suspected, you can also index to a whole month, by just giving the year and month:

temp['1988-01'].plot(ls='dotted', marker='.') 
despine(plt.gca()) 
plt.gcf().autofmt_xdate() 
plt.ylabel('Temperature'), 

Indexing and slicing

The variation within one month, here January, is quite large, around 20 degrees from minimum to maximum. You can also slice with two indexes, just like a normal array. Try making a plot for a few months by slicing, for example, temp['1988-06': '1989-06'].

Just as you can filter out certain values with a normal array, you can filter out certain values in a time series. To only get the values when the temperature was strictly below -25, you do like you always would—do a comparison that returns a Boolean array:

temp[temp < -25].head() 

Indexing and slicing

To finish off this section, make a plot with each year plotted in the same figure as follows:

Indexing and slicing

As could be strongly hinted at from the first plot of this data, it has a seasonal component, which is not at all surprising for such a dataset (outdoor temperature). However, try to make this plot yourself by slicing. Can you also add the months on the x axis? Perhaps try to make one for only one month but all years, say April or May. The next step that we will cover is how to manipulate and calculate various estimates on the time series.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset