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 - Extract the ordinal day of year from the DateTimeIndex with specific time series frequency
To extract the ordinal day of year from the DateTimeIndex with specific time series frequency, use the DateTimeIndex.dayofyear property. The ordinal day of year represents which day of the year it is (1-365 or 1-366 for leap years).
Creating DateTimeIndex with Time Series Frequency
First, let's create a DateTimeIndex with daily frequency and extract the day of year ?
import pandas as pd
# Create DatetimeIndex with period 6 and frequency as D (daily)
# The timezone is Australia/Sydney
datetimeindex = pd.date_range('2021-10-20 02:30:50', periods=6, tz='Australia/Sydney', freq='D')
# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)
# Display DateTimeIndex frequency
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)
# Get the ordinal day of year
print("\nOrdinal day of year...")
print(datetimeindex.dayofyear)
DateTimeIndex...
DatetimeIndex(['2021-10-20 02:30:50+11:00', '2021-10-21 02:30:50+11:00',
'2021-10-22 02:30:50+11:00', '2021-10-23 02:30:50+11:00',
'2021-10-24 02:30:50+11:00', '2021-10-25 02:30:50+11:00'],
dtype='datetime64[ns, Australia/Sydney]', freq='D')
DateTimeIndex frequency...
<Day>
Ordinal day of year...
Int64Index([293, 294, 295, 296, 297, 298], dtype='int64')
Different Time Series Frequencies
You can use various frequencies to create DateTimeIndex and extract day of year ?
import pandas as pd
# Weekly frequency
weekly_index = pd.date_range('2021-01-01', periods=4, freq='W')
print("Weekly DateTimeIndex:")
print(weekly_index)
print("Day of year:", weekly_index.dayofyear)
print("\n" + "="*50 + "\n")
# Monthly frequency
monthly_index = pd.date_range('2021-01-15', periods=3, freq='M')
print("Monthly DateTimeIndex:")
print(monthly_index)
print("Day of year:", monthly_index.dayofyear)
Weekly DateTimeIndex: DatetimeIndex(['2021-01-03', '2021-01-10', '2021-01-17', '2021-01-24'], dtype='datetime64[ns]', freq='W-SUN') Day of year: Int64Index([3, 10, 17, 24], dtype='int64') ================================================== Monthly DateTimeIndex: DatetimeIndex(['2021-01-31', '2021-02-28', '2021-03-31'], dtype='datetime64[ns]', freq='M') Day of year: Int64Index([31, 59, 90], dtype='int64')
Understanding the Output
The dayofyear property returns an Int64Index containing the ordinal day numbers. For example, October 20, 2021 is the 293rd day of the year, October 21 is the 294th day, and so on.
Conclusion
Use DateTimeIndex.dayofyear to extract ordinal day numbers from datetime indexes. This property works with any time series frequency and returns the day number within the year (1-365/366).
