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 - Change the frequency of the given Period object from Seconds to Daily frequency
To change the frequency of a Pandas Period object from seconds to daily frequency, use the period.asfreq() method with the parameter 'D'. This conversion aggregates time information to the day level.
Understanding Period Objects
A Pandas Period represents a specific time span with an associated frequency. When you convert from a higher frequency (seconds) to a lower frequency (daily), the result retains only the date component ?
import pandas as pd
# Create a Period object with seconds frequency
period = pd.Period(freq="S", year=2021, month=4, day=16, hour=2, minute=35, second=15)
print("Original Period (seconds frequency):")
print(period)
print("Frequency:", period.freq)
Original Period (seconds frequency): 2021-04-16 02:35:15 Frequency: S
Converting Frequency Using asfreq()
The asfreq() method converts the period to the specified frequency. When converting from seconds ('S') to daily ('D'), only the date portion is preserved ?
import pandas as pd
# Create Period with seconds frequency
period = pd.Period(freq="S", year=2021, month=4, day=16, hour=2, minute=35, second=15)
print("Before conversion:", period)
# Convert to daily frequency
daily_period = period.asfreq('D')
print("After conversion to daily:", daily_period)
print("New frequency:", daily_period.freq)
Before conversion: 2021-04-16 02:35:15 After conversion to daily: 2021-04-16 New frequency: D
Multiple Frequency Conversions
You can convert periods to various frequencies. Here's a comparison of different frequency conversions from the same seconds-level period ?
import pandas as pd
# Original period with seconds frequency
original = pd.Period(freq="S", year=2021, month=4, day=16, hour=2, minute=35, second=15)
conversions = {
'Original (S)': original,
'Minutes (T)': original.asfreq('T'),
'Hours (H)': original.asfreq('H'),
'Daily (D)': original.asfreq('D'),
'Monthly (M)': original.asfreq('M')
}
for label, period in conversions.items():
print(f"{label}: {period}")
Original (S): 2021-04-16 02:35:15 Minutes (T): 2021-04-16 02:35 Hours (H): 2021-04-16 02:00 Daily (D): 2021-04-16 Monthly (M): 2021-04
Comparison of Frequency Conversions
| Frequency Code | Description | Information Retained |
|---|---|---|
| S | Seconds | Full timestamp |
| T | Minutes | Year, month, day, hour, minute |
| H | Hours | Year, month, day, hour |
| D | Daily | Year, month, day |
| M | Monthly | Year, month |
Conclusion
Use period.asfreq('D') to convert any Period object to daily frequency. This conversion preserves only the date information, making it useful for daily aggregations and analysis.
