Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Convert Period to desired frequency
To convert Period to desired frequency, use the period.asfreq() method. This method allows you to change the frequency of a Pandas Period object to match your analysis requirements.
What is asfreq()?
The asfreq() method converts a Period from one frequency to another. When converting to a higher frequency (like daily to hourly), it uses specific rules to determine the exact timestamp within the period.
Creating Period Objects
First, let's create Period objects with different frequencies ?
import pandas as pd
# Create Period objects with different frequencies
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)
print("Period1:", period1)
print("Period2:", period2)
Period1: 2020-09-23 03:15:40 Period2: 2021-04-16
Converting to Hourly Frequency
Convert both periods to hourly frequency using the 'H' specifier ?
import pandas as pd
# Create Period objects
period1 = pd.Period("2020-09-23 03:15:40")
period2 = pd.Period(freq="D", year=2021, month=4, day=16, hour=2, minute=35)
# Convert to hourly frequency
res1 = period1.asfreq('H')
res2 = period2.asfreq('H')
print("Original Period1:", period1)
print("Converted to Hourly:", res1)
print("\nOriginal Period2:", period2)
print("Converted to Hourly:", res2)
Original Period1: 2020-09-23 03:15:40 Converted to Hourly: 2020-09-23 03:00 Original Period2: 2021-04-16 Converted to Hourly: 2021-04-16 23:00
Common Frequency Conversions
Here are examples of converting periods to different frequencies ?
import pandas as pd
# Create a daily period
daily_period = pd.Period("2023-03-15", freq="D")
# Convert to different frequencies
hourly = daily_period.asfreq('H') # Hourly
monthly = daily_period.asfreq('M') # Monthly
quarterly = daily_period.asfreq('Q') # Quarterly
print("Original Daily Period:", daily_period)
print("Hourly:", hourly)
print("Monthly:", monthly)
print("Quarterly:", quarterly)
Original Daily Period: 2023-03-15 Hourly: 2023-03-15 23:00 Monthly: 2023-03 Quarterly: 2023Q1
Frequency Specifiers
| Specifier | Description | Example |
|---|---|---|
| 'D' | Daily | 2023-03-15 |
| 'H' | Hourly | 2023-03-15 14:00 |
| 'M' | Monthly | 2023-03 |
| 'Q' | Quarterly | 2023Q1 |
| 'Y' | Yearly | 2023 |
Conclusion
The asfreq() method provides flexible Period frequency conversion in Pandas. Use it to align Period objects with your analysis timeframe, whether converting from daily to hourly or aggregating to monthly periods.
