Time Series / Date functionality¶
pandas has proven very successful as a tool for working with time series data, especially in the financial data analysis space. With the 0.8 release, we have further improved the time series API in pandas by leaps and bounds. Using the new NumPy datetime64 dtype, we have consolidated a large number of features from other Python libraries like scikits.timeseries as well as created a tremendous amount of new functionality for manipulating time series data.
In working with time series data, we will frequently seek to:
- generate sequences of fixed-frequency dates and time spans
- conform or convert time series to a particular frequency
- compute “relative” dates based on various non-standard time increments (e.g. 5 business days before the last business day of the year), or “roll” dates forward or backward
pandas provides a relatively compact and self-contained set of tools for performing the above tasks.
Create a range of dates:
# 72 hours starting with midnight Jan 1st, 2011
In [1067]: rng = date_range('1/1/2011', periods=72, freq='H')
In [1068]: rng[:5]
Out[1068]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2011-01-01 04:00:00]
Length: 5, Freq: H, Timezone: None
Index pandas objects with dates:
In [1069]: ts = Series(randn(len(rng)), index=rng)
In [1070]: ts.head()
Out[1070]:
2011-01-01 00:00:00 0.469112
2011-01-01 01:00:00 -0.282863
2011-01-01 02:00:00 -1.509059
2011-01-01 03:00:00 -1.135632
2011-01-01 04:00:00 1.212112
Freq: H
Change frequency and fill gaps:
# to 45 minute frequency and forward fill
In [1071]: converted = ts.asfreq('45Min', method='pad')
In [1072]: converted.head()
Out[1072]:
2011-01-01 00:00:00 0.469112
2011-01-01 00:45:00 0.469112
2011-01-01 01:30:00 -0.282863
2011-01-01 02:15:00 -1.509059
2011-01-01 03:00:00 -1.135632
Freq: 45T
Resample:
# Daily means
In [1073]: ts.resample('D', how='mean')
Out[1073]:
2011-01-01 0.469112
2011-01-02 -0.322252
2011-01-03 -0.317244
2011-01-04 0.083412
Freq: D
Time Stamps vs. Time Spans¶
Time-stamped data is the most basic type of timeseries data that associates values with points in time. For pandas objects it means using the points in time to create the index
In [1074]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]
In [1075]: ts = Series(np.random.randn(3), dates)
In [1076]: type(ts.index)
Out[1076]: pandas.tseries.index.DatetimeIndex
In [1077]: ts
Out[1077]:
2012-05-01 -0.410001
2012-05-02 -0.078638
2012-05-03 0.545952
However, in many cases it is more natural to associate things like change variables with a time span instead.
For example:
In [1078]: periods = PeriodIndex([Period('2012-01'), Period('2012-02'),
......: Period('2012-03')])
......:
In [1079]: ts = Series(np.random.randn(3), periods)
In [1080]: type(ts.index)
Out[1080]: pandas.tseries.period.PeriodIndex
In [1081]: ts
Out[1081]:
Jan-2012 -1.219217
Feb-2012 -1.226825
Mar-2012 0.769804
Freq: M
Starting with 0.8, pandas allows you to capture both representations and convert between them. Under the hood, pandas represents timestamps using instances of Timestamp and sequences of timestamps using instances of DatetimeIndex. For regular time spans, pandas uses Period objects for scalar values and PeriodIndex for sequences of spans. Better support for irregular intervals with arbitrary start and end points are forth-coming in future releases.
Generating Ranges of Timestamps¶
To generate an index with time stamps, you can use either the DatetimeIndex or Index constructor and pass in a list of datetime objects:
In [1082]: dates = [datetime(2012, 5, 1), datetime(2012, 5, 2), datetime(2012, 5, 3)]
In [1083]: index = DatetimeIndex(dates)
In [1084]: index # Note the frequency information
Out[1084]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-05-01 00:00:00, ..., 2012-05-03 00:00:00]
Length: 3, Freq: None, Timezone: None
In [1085]: index = Index(dates)
In [1086]: index # Automatically converted to DatetimeIndex
Out[1086]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-05-01 00:00:00, ..., 2012-05-03 00:00:00]
Length: 3, Freq: None, Timezone: None
Practically, this becomes very cumbersome because we often need a very long index with a large number of timestamps. If we need timestamps on a regular frequency, we can use the pandas functions date_range and bdate_range to create timestamp indexes.
In [1087]: index = date_range('2000-1-1', periods=1000, freq='M')
In [1088]: index
Out[1088]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2000-01-31 00:00:00, ..., 2083-04-30 00:00:00]
Length: 1000, Freq: M, Timezone: None
In [1089]: index = bdate_range('2012-1-1', periods=250)
In [1090]: index
Out[1090]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-02 00:00:00, ..., 2012-12-14 00:00:00]
Length: 250, Freq: B, Timezone: None
Convenience functions like date_range and bdate_range utilizes a variety of frequency aliases. The default frequency for date_range is a calendar day while the default for bdate_range is a business day
In [1091]: start = datetime(2011, 1, 1)
In [1092]: end = datetime(2012, 1, 1)
In [1093]: rng = date_range(start, end)
In [1094]: rng
Out[1094]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2012-01-01 00:00:00]
Length: 366, Freq: D, Timezone: None
In [1095]: rng = bdate_range(start, end)
In [1096]: rng
Out[1096]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-03 00:00:00, ..., 2011-12-30 00:00:00]
Length: 260, Freq: B, Timezone: None
date_range and bdate_range makes it easy to generate a range of dates using various combinations of its parameters like start, end, periods, and freq:
In [1097]: date_range(start, end, freq='BM')
Out[1097]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-31 00:00:00, ..., 2011-12-30 00:00:00]
Length: 12, Freq: BM, Timezone: None
In [1098]: date_range(start, end, freq='W')
Out[1098]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-02 00:00:00, ..., 2012-01-01 00:00:00]
Length: 53, Freq: W-SUN, Timezone: None
In [1099]: bdate_range(end=end, periods=20)
Out[1099]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-12-05 00:00:00, ..., 2011-12-30 00:00:00]
Length: 20, Freq: B, Timezone: None
In [1100]: bdate_range(start=start, periods=20)
Out[1100]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-03 00:00:00, ..., 2011-01-28 00:00:00]
Length: 20, Freq: B, Timezone: None
The start and end dates are strictly inclusive. So it will not generate any dates outside of those dates if specified.
DatetimeIndex¶
One of the main uses for DatetimeIndex is as an index for pandas objects. The DatetimeIndex class contains many timeseries related optimizations:
- A large range of dates for various offsets are pre-computed and cached under the hood in order to make generating subsequent date ranges very fast (just have to grab a slice)
- Fast shifting using the shift and tshift method on pandas objects
- Unioning of overlapping DatetimeIndex objects with the same frequency is very fast (important for fast data alignment)
- Quick access to date fields via properties such as year, month, etc.
- Regularization functions like snap and very fast asof logic
DatetimeIndex can be used like a regular index and offers all of its intelligent functionality like selection, slicing, etc.
In [1101]: rng = date_range(start, end, freq='BM')
In [1102]: ts = Series(randn(len(rng)), index=rng)
In [1103]: ts.index
Out[1103]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-31 00:00:00, ..., 2011-12-30 00:00:00]
Length: 12, Freq: BM, Timezone: None
In [1104]: ts[:5].index
Out[1104]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-31 00:00:00, ..., 2011-05-31 00:00:00]
Length: 5, Freq: BM, Timezone: None
In [1105]: ts[::2].index
Out[1105]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-31 00:00:00, ..., 2011-11-30 00:00:00]
Length: 6, Freq: 2BM, Timezone: None
You can pass in dates and strings that parses to dates as indexing parameters:
In [1106]: ts['1/31/2011']
Out[1106]: -1.2812473076599531
In [1107]: ts[datetime(2011, 12, 25):]
Out[1107]:
2011-12-30 0.687738
Freq: BM
In [1108]: ts['10/31/2011':'12/31/2011']
Out[1108]:
2011-10-31 0.149748
2011-11-30 -0.732339
2011-12-30 0.687738
Freq: BM
A truncate convenience function is provided that is equivalent to slicing:
In [1109]: ts.truncate(before='10/31/2011', after='12/31/2011')
Out[1109]:
2011-10-31 0.149748
2011-11-30 -0.732339
2011-12-30 0.687738
Freq: BM
To provide convenience for accessing longer time series, you can also pass in the year or year and month as strings:
In [1110]: ts['2011']
Out[1110]:
2011-01-31 -1.281247
2011-02-28 -0.727707
2011-03-31 -0.121306
2011-04-29 -0.097883
2011-05-31 0.695775
2011-06-30 0.341734
2011-07-29 0.959726
2011-08-31 -1.110336
2011-09-30 -0.619976
2011-10-31 0.149748
2011-11-30 -0.732339
2011-12-30 0.687738
Freq: BM
In [1111]: ts['2011-6']
Out[1111]:
2011-06-30 0.341734
Freq: BM
Even complicated fancy indexing that breaks the DatetimeIndex’s frequency regularity will result in a DatetimeIndex (but frequency is lost):
In [1112]: ts[[0, 2, 6]].index
Out[1112]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-31 00:00:00, ..., 2011-07-29 00:00:00]
Length: 3, Freq: None, Timezone: None
DatetimeIndex objects has all the basic functionality of regular Index objects and a smorgasbord of advanced timeseries-specific methods for easy frequency processing.
See also
Note
While pandas does not force you to have a sorted date index, some of these methods may have unexpected or incorrect behavior if the dates are unsorted. So please be careful.
DateOffset objects¶
In the preceding examples, we created DatetimeIndex objects at various frequencies by passing in frequency strings like ‘M’, ‘W’, and ‘BM to the freq keyword. Under the hood, these frequency strings are being translated into an instance of pandas DateOffset, which represents a regular frequency increment. Specific offset logic like “month”, “business day”, or “one hour” is represented in its various subclasses.
Class name | Description |
---|---|
DateOffset | Generic offset class, defaults to 1 calendar day |
BDay | business day (weekday) |
Week | one week, optionally anchored on a day of the week |
WeekOfMonth | the x-th day of the y-th week of each month |
MonthEnd | calendar month end |
MonthBegin | calendar month begin |
BMonthEnd | business month end |
BMonthBegin | business month begin |
QuarterEnd | calendar quarter end |
QuarterBegin | calendar quarter begin |
BQuarterEnd | business quarter end |
BQuarterBegin | business quarter begin |
YearEnd | calendar year end |
YearBegin | calendar year begin |
BYearEnd | business year end |
BYearBegin | business year begin |
Hour | one hour |
Minute | one minute |
Second | one second |
Milli | one millisecond |
Micro | one microsecond |
The basic DateOffset takes the same arguments as dateutil.relativedelta, which works like:
In [1113]: d = datetime(2008, 8, 18)
In [1114]: d + relativedelta(months=4, days=5)
Out[1114]: datetime.datetime(2008, 12, 23, 0, 0)
We could have done the same thing with DateOffset:
In [1115]: from pandas.tseries.offsets import *
In [1116]: d + DateOffset(months=4, days=5)
Out[1116]: datetime.datetime(2008, 12, 23, 0, 0)
The key features of a DateOffset object are:
- it can be added / subtracted to/from a datetime object to obtain a shifted date
- it can be multiplied by an integer (positive or negative) so that the increment will be applied multiple times
- it has rollforward and rollback methods for moving a date forward or backward to the next or previous “offset date”
Subclasses of DateOffset define the apply function which dictates custom date increment logic, such as adding business days:
class BDay(DateOffset):
"""DateOffset increments between business days"""
def apply(self, other):
...
In [1117]: d - 5 * BDay()
Out[1117]: datetime.datetime(2008, 8, 11, 0, 0)
In [1118]: d + BMonthEnd()
Out[1118]: datetime.datetime(2008, 8, 29, 0, 0)
The rollforward and rollback methods do exactly what you would expect:
In [1119]: d
Out[1119]: datetime.datetime(2008, 8, 18, 0, 0)
In [1120]: offset = BMonthEnd()
In [1121]: offset.rollforward(d)
Out[1121]: datetime.datetime(2008, 8, 29, 0, 0)
In [1122]: offset.rollback(d)
Out[1122]: datetime.datetime(2008, 7, 31, 0, 0)
It’s definitely worth exploring the pandas.tseries.offsets module and the various docstrings for the classes.
Parametric offsets¶
Some of the offsets can be “parameterized” when created to result in different behavior. For example, the Week offset for generating weekly data accepts a weekday parameter which results in the generated dates always lying on a particular day of the week:
In [1123]: d + Week()
Out[1123]: datetime.datetime(2008, 8, 25, 0, 0)
In [1124]: d + Week(weekday=4)
Out[1124]: datetime.datetime(2008, 8, 22, 0, 0)
In [1125]: (d + Week(weekday=4)).weekday()
Out[1125]: 4
Another example is parameterizing YearEnd with the specific ending month:
In [1126]: d + YearEnd()
Out[1126]: datetime.datetime(2008, 12, 31, 0, 0)
In [1127]: d + YearEnd(month=6)
Out[1127]: datetime.datetime(2009, 6, 30, 0, 0)
Offset Aliases¶
A number of string aliases are given to useful common time series frequencies. We will refer to these aliases as offset aliases (referred to as time rules prior to v0.8.0).
Alias | Description |
---|---|
B | business day frequency |
D | calendar day frequency |
W | weekly frequency |
M | month end frequency |
BM | business month end frequency |
MS | month start frequency |
BMS | business month start frequency |
Q | quarter end frequency |
BQ | business quarter endfrequency |
QS | quarter start frequency |
BQS | business quarter start frequency |
A | year end frequency |
BA | business year end frequency |
AS | year start frequency |
BAS | business year start frequency |
H | hourly frequency |
T | minutely frequency |
S | secondly frequency |
L | milliseonds |
U | microseconds |
Combining Aliases¶
As we have seen previously, the alias and the offset instance are fungible in most functions:
In [1128]: date_range(start, periods=5, freq='B')
Out[1128]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-03 00:00:00, ..., 2011-01-07 00:00:00]
Length: 5, Freq: B, Timezone: None
In [1129]: date_range(start, periods=5, freq=BDay())
Out[1129]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-03 00:00:00, ..., 2011-01-07 00:00:00]
Length: 5, Freq: B, Timezone: None
You can combine together day and intraday offsets:
In [1130]: date_range(start, periods=10, freq='2h20min')
Out[1130]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2011-01-01 21:00:00]
Length: 10, Freq: 140T, Timezone: None
In [1131]: date_range(start, periods=10, freq='1D10U')
Out[1131]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2011-01-01 00:00:00, ..., 2011-01-10 00:00:00.000090]
Length: 10, Freq: 86400000010U, Timezone: None
Anchored Offsets¶
For some frequencies you can specify an anchoring suffix:
Alias | Description |
---|---|
W-SUN | weekly frequency (sundays). Same as ‘W’ |
W-MON | weekly frequency (mondays) |
W-TUE | weekly frequency (tuesdays) |
W-WED | weekly frequency (wednesdays) |
W-THU | weekly frequency (thursdays) |
W-FRI | weekly frequency (fridays) |
W-SAT | weekly frequency (saturdays) |
(B)Q(S)-DEC | quarterly frequency, year ends in December. Same as ‘Q’ |
(B)Q(S)-JAN | quarterly frequency, year ends in January |
(B)Q(S)-FEB | quarterly frequency, year ends in February |
(B)Q(S)-MAR | quarterly frequency, year ends in March |
(B)Q(S)-APR | quarterly frequency, year ends in April |
(B)Q(S)-MAY | quarterly frequency, year ends in May |
(B)Q(S)-JUN | quarterly frequency, year ends in June |
(B)Q(S)-JUL | quarterly frequency, year ends in July |
(B)Q(S)-AUG | quarterly frequency, year ends in August |
(B)Q(S)-SEP | quarterly frequency, year ends in September |
(B)Q(S)-OCT | quarterly frequency, year ends in October |
(B)Q(S)-NOV | quarterly frequency, year ends in November |
(B)A(S)-DEC | annual frequency, anchored end of December. Same as ‘A’ |
(B)A(S)-JAN | annual frequency, anchored end of January |
(B)A(S)-FEB | annual frequency, anchored end of February |
(B)A(S)-MAR | annual frequency, anchored end of March |
(B)A(S)-APR | annual frequency, anchored end of April |
(B)A(S)-MAY | annual frequency, anchored end of May |
(B)A(S)-JUN | annual frequency, anchored end of June |
(B)A(S)-JUL | annual frequency, anchored end of July |
(B)A(S)-AUG | annual frequency, anchored end of August |
(B)A(S)-SEP | annual frequency, anchored end of September |
(B)A(S)-OCT | annual frequency, anchored end of October |
(B)A(S)-NOV | annual frequency, anchored end of November |
These can be used as arguments to date_range, bdate_range, constructors for DatetimeIndex, as well as various other timeseries-related functions in pandas.
Legacy Aliases¶
Note that prior to v0.8.0, time rules had a slightly different look. Pandas will continue to support the legacy time rules for the time being but it is strongly recommended that you switch to using the new offset aliases.
Legacy Time Rule | Offset Alias |
---|---|
WEEKDAY | B |
EOM | BM |
W@MON | W-MON |
W@TUE | W-TUE |
W@WED | W-WED |
W@THU | W-THU |
W@FRI | W-FRI |
W@SAT | W-SAT |
W@SUN | W-SUN |
Q@JAN | BQ-JAN |
Q@FEB | BQ-FEB |
Q@MAR | BQ-MAR |
A@JAN | BA-JAN |
A@FEB | BA-FEB |
A@MAR | BA-MAR |
A@APR | BA-APR |
A@MAY | BA-MAY |
A@JUN | BA-JUN |
A@JUL | BA-JUL |
A@AUG | BA-AUG |
A@SEP | BA-SEP |
A@OCT | BA-OCT |
A@NOV | BA-NOV |
A@DEC | BA-DEC |
min | T |
ms | L |
us: “U” |
As you can see, legacy quarterly and annual frequencies are business quarter and business year ends. Please also note the legacy time rule for milliseconds ms versus the new offset alias for month start MS. This means that offset alias parsing is case sensitive.
Up- and downsampling¶
With 0.8, pandas introduces simple, powerful, and efficient functionality for performing resampling operations during frequency conversion (e.g., converting secondly data into 5-minutely data). This is extremely common in, but not limited to, financial applications.
In [1142]: rng = date_range('1/1/2012', periods=100, freq='S')
In [1143]: ts = Series(randint(0, 500, len(rng)), index=rng)
In [1144]: ts.resample('5Min', how='sum')
Out[1144]:
2012-01-01 00:00:00 230
2012-01-01 00:05:00 25562
Freq: 5T
The resample function is very flexible and allows you to specify many different parameters to control the frequency conversion and resampling operation.
The how parameter can be a function name or numpy array function that takes and array and produces an aggregated values:
In [1145]: ts.resample('5Min') # default is mean
Out[1145]:
2012-01-01 00:00:00 230.00000
2012-01-01 00:05:00 258.20202
Freq: 5T
In [1146]: ts.resample('5Min', how='ohlc')
Out[1146]:
open high low close
2012-01-01 00:00:00 230 230 230 230
2012-01-01 00:05:00 202 492 0 214
In [1147]: ts.resample('5Min', how=np.max)
Out[1147]:
2012-01-01 00:00:00 230
2012-01-01 00:05:00 492
Any function available via dispatching can be given to the how parameter by name, including sum, mean, std, max, min, median, first, last, ohlc.
For downsampling, closed can be set to ‘left’ or ‘right’ to specify which end of the interval is closed:
In [1148]: ts.resample('5Min', closed='right')
Out[1148]:
2012-01-01 00:00:00 230.00000
2012-01-01 00:05:00 258.20202
Freq: 5T
In [1149]: ts.resample('5Min', closed='left')
Out[1149]:
2012-01-01 00:05:00 257.92
Freq: 5T
For upsampling, the fill_method and limit parameters can be specified to interpolate over the gaps that are created:
# from secondly to every 250 milliseconds
In [1150]: ts[:2].resample('250L')
Out[1150]:
2012-01-01 00:00:00 230
2012-01-01 00:00:00.250000 NaN
2012-01-01 00:00:00.500000 NaN
2012-01-01 00:00:00.750000 NaN
2012-01-01 00:00:01 202
Freq: 250L
In [1151]: ts[:2].resample('250L', fill_method='pad')
Out[1151]:
2012-01-01 00:00:00 230
2012-01-01 00:00:00.250000 230
2012-01-01 00:00:00.500000 230
2012-01-01 00:00:00.750000 230
2012-01-01 00:00:01 202
Freq: 250L
In [1152]: ts[:2].resample('250L', fill_method='pad', limit=2)
Out[1152]:
2012-01-01 00:00:00 230
2012-01-01 00:00:00.250000 230
2012-01-01 00:00:00.500000 230
2012-01-01 00:00:00.750000 NaN
2012-01-01 00:00:01 202
Freq: 250L
Parameters like label and loffset are used to manipulate the resulting labels. label specifies whether the result is labeled with the beginning or the end of the interval. loffset performs a time adjustment on the output labels.
In [1153]: ts.resample('5Min') # by default label='right'
Out[1153]:
2012-01-01 00:00:00 230.00000
2012-01-01 00:05:00 258.20202
Freq: 5T
In [1154]: ts.resample('5Min', label='left')
Out[1154]:
2011-12-31 23:55:00 230.00000
2012-01-01 00:00:00 258.20202
Freq: 5T
In [1155]: ts.resample('5Min', label='left', loffset='1s')
Out[1155]:
2011-12-31 23:55:01 230.00000
2012-01-01 00:00:01 258.20202
The axis parameter can be set to 0 or 1 and allows you to resample the specified axis for a DataFrame.
kind can be set to ‘timestamp’ or ‘period’ to convert the resulting index to/from time-stamp and time-span representations. By default resample retains the input representation.
convention can be set to ‘start’ or ‘end’ when resampling period data (detail below). It specifies how low frequency periods are converted to higher frequency periods.
Note that 0.8 marks a watershed in the timeseries functionality in pandas. In previous versions, resampling had to be done using a combination of date_range, groupby with asof, and then calling an aggregation function on the grouped object. This was not nearly convenient or performant as the new pandas timeseries API.
Time Span Representation¶
Regular intervals of time are represented by Period objects in pandas while sequences of Period objects are collected in a PeriodIndex, which can be created with the convenience function period_range.
Period¶
A Period represents a span of time (e.g., a day, a month, a quarter, etc). It can be created using a frequency alias:
In [1156]: Period('2012', freq='A-DEC')
Out[1156]: Period('2012', 'A-DEC')
In [1157]: Period('2012-1-1', freq='D')
Out[1157]: Period('01-Jan-2012', 'D')
In [1158]: Period('2012-1-1 19:00', freq='H')
Out[1158]: Period('01-Jan-2012 19:00', 'H')
Unlike time stamped data, pandas does not support frequencies at multiples of DateOffsets (e.g., ‘3Min’) for periods.
Adding and subtracting integers from periods shifts the period by its own frequency.
In [1159]: p = Period('2012', freq='A-DEC')
In [1160]: p + 1
Out[1160]: Period('2013', 'A-DEC')
In [1161]: p - 3
Out[1161]: Period('2009', 'A-DEC')
Taking the difference of Period instances with the same frequency will return the number of frequency units between them:
In [1162]: Period('2012', freq='A-DEC') - Period(2002', freq='A-DEC')
File "<ipython-input-1162-41a08553f136>", line 1
Period('2012', freq='A-DEC') - Period(2002', freq='A-DEC')
^
SyntaxError: invalid syntax
PeriodIndex and period_range¶
Regular sequences of Period objects can be collected in a PeriodIndex, which can be constructed using the period_range convenience function:
In [1163]: prng = period_range('1/1/2011', '1/1/2012', freq='M')
In [1164]: prng
Out[1164]:
<class 'pandas.tseries.period.PeriodIndex'>
freq: M
[Jan-2011, ..., Jan-2012]
length: 13
The PeriodIndex constructor can also be used directly:
In [1165]: PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')
Out[1165]:
<class 'pandas.tseries.period.PeriodIndex'>
freq: M
[Jan-2011, ..., Mar-2011]
length: 3
Just like DatetimeIndex, a PeriodIndex can also be used to index pandas objects:
In [1166]: Series(randn(len(prng)), prng)
Out[1166]:
Jan-2011 0.301624
Feb-2011 -1.460489
Mar-2011 0.610679
Apr-2011 1.195856
May-2011 -0.008820
Jun-2011 -0.045729
Jul-2011 -1.051015
Aug-2011 -0.422924
Sep-2011 -0.028361
Oct-2011 -0.782386
Nov-2011 0.861980
Dec-2011 1.438604
Jan-2012 -0.525492
Freq: M
Frequency Conversion and Resampling with PeriodIndex¶
The frequency of Periods and PeriodIndex can be converted via the asfreq method. Let’s start with the fiscal year 2011, ending in December:
In [1167]: p = Period('2011', freq='A-DEC')
In [1168]: p
Out[1168]: Period('2011', 'A-DEC')
We can convert it to a monthly frequency. Using the how parameter, we can specify whether to return the starting or ending month:
In [1169]: p.asfreq('M', how='start')
Out[1169]: Period('Jan-2011', 'M')
In [1170]: p.asfreq('M', how='end')
Out[1170]: Period('Dec-2011', 'M')
The shorthands ‘s’ and ‘e’ are provided for convenience:
In [1171]: p.asfreq('M', 's')
Out[1171]: Period('Jan-2011', 'M')
In [1172]: p.asfreq('M', 'e')
Out[1172]: Period('Dec-2011', 'M')
Converting to a “super-period” (e.g., annual frequency is a super-period of quarterly frequency) automatically returns the super-period that includes the input period:
In [1173]: p = Period('2011-12', freq='M')
In [1174]: p.asfreq('A-NOV')
Out[1174]: Period('2012', 'A-NOV')
Note that since we converted to an annual frequency that ends the year in November, the monthly period of December 2011 is actually in the 2012 A-NOV period.
Period conversions with anchored frequencies are particularly useful for working with various quarterly data common to economics, business, and other fields. Many organizations define quarters relative to the month in which their fiscal year start and ends. Thus, first quarter of 2011 could start in 2010 or a few months into 2011. Via anchored frequencies, pandas works all quarterly frequencies Q-JAN through Q-DEC.
Q-DEC define regular calendar quarters:
In [1175]: p = Period('2012Q1', freq='Q-DEC')
In [1176]: p.asfreq('D', 's')
Out[1176]: Period('01-Jan-2012', 'D')
In [1177]: p.asfreq('D', 'e')
Out[1177]: Period('31-Mar-2012', 'D')
Q-MAR defines fiscal year end in March:
In [1178]: p = Period('2011Q4', freq='Q-MAR')
In [1179]: p.asfreq('D', 's')
Out[1179]: Period('01-Jan-2011', 'D')
In [1180]: p.asfreq('D', 'e')
Out[1180]: Period('31-Mar-2011', 'D')
Converting between Representations¶
Timestamped data can be converted to PeriodIndex-ed data using to_period and vice-versa using to_timestamp:
In [1181]: rng = date_range('1/1/2012', periods=5, freq='M')
In [1182]: ts = Series(randn(len(rng)), index=rng)
In [1183]: ts
Out[1183]:
2012-01-31 -1.684469
2012-02-29 0.550605
2012-03-31 0.091955
2012-04-30 0.891713
2012-05-31 0.807078
Freq: M
In [1184]: ps = ts.to_period()
In [1185]: ps
Out[1185]:
Jan-2012 -1.684469
Feb-2012 0.550605
Mar-2012 0.091955
Apr-2012 0.891713
May-2012 0.807078
Freq: M
In [1186]: ps.to_timestamp()
Out[1186]:
2012-01-31 -1.684469
2012-02-29 0.550605
2012-03-31 0.091955
2012-04-30 0.891713
2012-05-31 0.807078
Freq: M
Remember that ‘s’ and ‘e’ can be used to return the timestamps at the start or end of the period:
In [1187]: ps.to_timestamp('D', how='s')
Out[1187]:
2012-01-01 -1.684469
2012-02-01 0.550605
2012-03-01 0.091955
2012-04-01 0.891713
2012-05-01 0.807078
Freq: MS
Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end:
In [1188]: prng = period_range('1990Q1', '2000Q4', freq='Q-NOV')
In [1189]: ts = Series(randn(len(prng)), prng)
In [1190]: ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
In [1191]: ts.head()
Out[1191]:
01-Mar-1990 09:00 0.221441
01-Jun-1990 09:00 -0.113139
01-Sep-1990 09:00 -1.812900
01-Dec-1990 09:00 -0.053708
01-Mar-1991 09:00 -0.114574
Freq: H
Time Zone Handling¶
Using pytz, pandas provides rich support for working with timestamps in different time zones. By default, pandas objects are time zone unaware:
In [1192]: rng = date_range('3/6/2012 00:00', periods=15, freq='D')
In [1193]: print(rng.tz)
None
To supply the time zone, you can use the tz keyword to date_range and other functions:
In [1194]: rng_utc = date_range('3/6/2012 00:00', periods=10, freq='D', tz='UTC')
In [1195]: print(rng_utc.tz)
UTC
Timestamps, like Python’s datetime.datetime object can be either time zone naive or time zone aware. Naive time series and DatetimeIndex objects can be localized using tz_localize:
In [1196]: ts = Series(randn(len(rng)), rng)
In [1197]: ts_utc = ts.tz_localize('UTC')
In [1198]: ts_utc
Out[1198]:
2012-03-06 00:00:00+00:00 -0.114722
2012-03-07 00:00:00+00:00 0.168904
2012-03-08 00:00:00+00:00 -0.048048
2012-03-09 00:00:00+00:00 0.801196
2012-03-10 00:00:00+00:00 1.392071
2012-03-11 00:00:00+00:00 -0.048788
2012-03-12 00:00:00+00:00 -0.808838
2012-03-13 00:00:00+00:00 -1.003677
2012-03-14 00:00:00+00:00 -0.160766
2012-03-15 00:00:00+00:00 1.758853
2012-03-16 00:00:00+00:00 0.729195
2012-03-17 00:00:00+00:00 1.359732
2012-03-18 00:00:00+00:00 2.006296
2012-03-19 00:00:00+00:00 0.870210
2012-03-20 00:00:00+00:00 0.043464
Freq: D
You can use the tz_convert method to convert pandas objects to convert tz-aware data to another time zone:
In [1199]: ts_utc.tz_convert('US/Eastern')
Out[1199]:
2012-03-05 19:00:00-05:00 -0.114722
2012-03-06 19:00:00-05:00 0.168904
2012-03-07 19:00:00-05:00 -0.048048
2012-03-08 19:00:00-05:00 0.801196
2012-03-09 19:00:00-05:00 1.392071
2012-03-10 19:00:00-05:00 -0.048788
2012-03-11 20:00:00-04:00 -0.808838
2012-03-12 20:00:00-04:00 -1.003677
2012-03-13 20:00:00-04:00 -0.160766
2012-03-14 20:00:00-04:00 1.758853
2012-03-15 20:00:00-04:00 0.729195
2012-03-16 20:00:00-04:00 1.359732
2012-03-17 20:00:00-04:00 2.006296
2012-03-18 20:00:00-04:00 0.870210
2012-03-19 20:00:00-04:00 0.043464
Freq: D
Under the hood, all timestamps are stored in UTC. Scalar values from a DatetimeIndex with a time zone will have their fields (day, hour, minute) localized to the time zone. However, timestamps with the same UTC value are still considered to be equal even if they are in different time zones:
In [1200]: rng_eastern = rng_utc.tz_convert('US/Eastern')
In [1201]: rng_berlin = rng_utc.tz_convert('Europe/Berlin')
In [1202]: rng_eastern[5]
Out[1202]: <Timestamp: 2012-03-10 19:00:00-0500 EST, tz=US/Eastern>
In [1203]: rng_berlin[5]
Out[1203]: <Timestamp: 2012-03-11 01:00:00+0100 CET, tz=Europe/Berlin>
In [1204]: rng_eastern[5] == rng_berlin[5]
Out[1204]: True
Like Series, DataFrame, and DatetimeIndex, Timestamps can be converted to other time zones using tz_convert:
In [1205]: rng_eastern[5]
Out[1205]: <Timestamp: 2012-03-10 19:00:00-0500 EST, tz=US/Eastern>
In [1206]: rng_berlin[5]
Out[1206]: <Timestamp: 2012-03-11 01:00:00+0100 CET, tz=Europe/Berlin>
In [1207]: rng_eastern[5].tz_convert('Europe/Berlin')
Out[1207]: <Timestamp: 2012-03-11 01:00:00+0100 CET, tz=Europe/Berlin>
Localization of Timestamps functions just like DatetimeIndex and TimeSeries:
In [1208]: rng[5]
Out[1208]: <Timestamp: 2012-03-11 00:00:00>
In [1209]: rng[5].tz_localize('Asia/Shanghai')
Out[1209]: <Timestamp: 2012-03-11 00:00:00+0800 CST, tz=Asia/Shanghai>
Operations between TimeSeries in difficult time zones will yield UTC TimeSeries, aligning the data on the UTC timestamps:
In [1210]: eastern = ts_utc.tz_convert('US/Eastern')
In [1211]: berlin = ts_utc.tz_convert('Europe/Berlin')
In [1212]: result = eastern + berlin
In [1213]: result
Out[1213]:
2012-03-06 00:00:00+00:00 -0.229443
2012-03-07 00:00:00+00:00 0.337809
2012-03-08 00:00:00+00:00 -0.096096
2012-03-09 00:00:00+00:00 1.602392
2012-03-10 00:00:00+00:00 2.784142
2012-03-11 00:00:00+00:00 -0.097575
2012-03-12 00:00:00+00:00 -1.617677
2012-03-13 00:00:00+00:00 -2.007353
2012-03-14 00:00:00+00:00 -0.321532
2012-03-15 00:00:00+00:00 3.517706
2012-03-16 00:00:00+00:00 1.458389
2012-03-17 00:00:00+00:00 2.719465
2012-03-18 00:00:00+00:00 4.012592
2012-03-19 00:00:00+00:00 1.740419
2012-03-20 00:00:00+00:00 0.086928
Freq: D
In [1214]: result.index
Out[1214]:
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-03-06 00:00:00, ..., 2012-03-20 00:00:00]
Length: 15, Freq: D, Timezone: UTC