Python | Pandas Series.dt.to_period

Опубликовано: 27 Марта, 2022

Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.to_period() function cast the underlying data of the given Series object to PeriodArray/Index at a particular frequency.

Syntax: Series.dt.to_period(*args, **kwargs)

Parameter :

freq : string or Offset, optional

Returns : PeriodArray/Index

Example #1: Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["2012-12-31", "2019-1-1 12:30", "2008-02-2 10:30",
               "2010-1-1 09:25", "2019-12-31 00:00"])
  
# Creating the index
idx = ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5"]
  
# set the index
sr.index = idx
  
# Convert the underlying data to datetime 
sr = pd.to_datetime(sr)
  
# Print the series
print(sr)

Выход :

Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at Weekly frequency.

# cast to targert frequency
result = sr.dt.to_period(freq = "W"
  
# print the result
print(result)

Выход :

As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency.

Example #2 : Use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency.

Выход :

Now we will use Series.dt.to_period() function to cast the underlying data of the given series object to Index at two year frequency.

# cast to targert frequency
result = sr.dt.to_period(freq = "2Y"
  
# print the result
print(result)

Выход :

As we can see in the output, the Series.dt.to_period() function has successfully cast the data to the target frequency.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.