Time Series Indexes—Creating Indexes
Discover the different ways of generating time series indexes in pandas.
We'll cover the following
Introduction
For time series data, it’s typical to represent the time component in the index of a Series
or a DataFrame so that data manipulation can be performed with respect to the time element. A time series index is a data structure representing a one-dimensional indexed array of date-time values.
The benefit of using time series indexes is that they offer the basic functionality of regular index objects. This includes providing a range of capabilities for time-based operations, such as resampling, slicing, and indexing by partial string matching. We’ll be looking at the three index objects associated with time series, namely the DatetimeIndex
, TimedeltaIndex
, and PeriodIndex
.
DatetimeIndex
The DatetimeIndex
index object corresponds to the concept of date times and is the most common type of time series index that we’ll encounter. To set a DatetimeIndex
, we can use the to_datetime()
function to convert a DataFrame column into the datetime64
data type, and then set it as the DataFrame index with set_index()
.
In the example below, we see how we can use to_datetime()
to convert a DataFrame column of date strings into a data type of datetime64[ns]
. As a result, the output DataFrame has a DatetimeIndex
that can be used for time-based operations, as shown below:
Get hands-on with 1400+ tech skills courses.