How to access datetime indexed elements in pandas series?


Pandas series is a one-dimensional ndarray type object which stores elements with labels, those labels are used to addressing the elements present in the pandas Series.

The labels are represented with integers, string, DateTime, and more. Here we will see how to access the series elements if the indexes are labeled with DateTime values.

Example

import pandas as pd

# creating dates
date = pd.date_range("2021-01-01", periods=5, freq="D")

# creating pandas Series with date index
series = pd.Series(range(10,len(date)+10), index=date)

print(series)

print('
') # get elements print(series['2021-01-01'])

Explanation

The variable date is storing the list of dates with length 5, the starting date is 2021-01-01 and the ending date is 2021-01-05. Those dates are created by using the pandas date_range function. By using this list of dates we have created a pandas series object (series) with 10,11,12,13,14 values and labels are dates.

Output

2021-01-01 10
2021-01-02 11
2021-01-03 12
2021-01-04 13
2021-01-05 14
Freq: D, dtype: int64


10

In this following example, the value 10 is displayed for the label indexed '2021-01-01'. In this same way, we can access elements in between dates (series[‘2021-01-01’: ‘2021-01-05’])

Example

This example for accessing elements based on a particular month.

import pandas as pd

# creating dates
date = pd.date_range(start ='01-03-2020', end ='1-1-2021', periods=10)

# creating pandas Series with date index
series = pd.Series(date.month_name(), index=date)

print(series)

print('
') # get elements print(series['2020-03'])

Explanation

The series object is storing data with DateTime indexed labels and names of their respective moths. Initially, this series object is created by using the pandas date_range module.

And the data present in this series are names of months of respected index labels that are generated by using the month_name() function in the pandas DateTime module.

Output

2020-01-03 00:00:00     January
2020-02-12 10:40:00    February
2020-03-23 21:20:00       March
2020-05-03 08:00:00         May
2020-06-12 18:40:00        June
2020-07-23 05:20:00        July
2020-09-01 16:00:00   September
2020-10-12 02:40:00     October
2020-11-21 13:20:00    November
2021-01-01 00:00:00     January
dtype: object


2020-03-23 21:20:00 March
dtype: object

The output march is series elements accessed by specifying the year and month values (series['2020-03']). The above output block has an entire series object and a single accessed element.

Updated on: 18-Nov-2021

831 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements