O'Reilly logo

Mastering pandas for Finance by Michael Heydt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Frequency conversion of time-series data

The frequency of the data in a time-series can be converted in pandas using the .asfreq() method of a Series or DataFrame. To demonstrate, we will use the following small subset of the MSFT stock closing values:

In [39]:
   sample = msftAC[:2]
   sample

Out[39]:
   Date
   2012-01-03    24.42183
   2012-01-04    24.99657
   Name: Adj Close, dtype: float64

We have extracted the first 2 days of adjusted close values. Let's suppose we want to resample this to have hourly sampling of data in-between the index labels. We can do this with the following command:

In [40]:
   sample.asfreq("H")

Out[40]:
   2012-01-03 00:00:00    24.42183
   2012-01-03 01:00:00         NaN
   2012-01-03 02:00:00         NaN
                            ...   
   2012-01-03 22:00:00         NaN
 2012-01-03 23:00:00 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required