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 - Indicate whether the date in DateTimeIndex is the first day of the year
To check whether the date in DateTimeIndex is the first day of the year, use the DateTimeIndex.is_year_start property. This property returns a boolean array indicating which dates are January 1st.
Syntax
DateTimeIndex.is_year_start
Creating a DateTimeIndex
First, let's create a DateTimeIndex that spans across a year boundary to demonstrate the property ?
import pandas as pd
# Create DateTimeIndex spanning year boundary
datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='1D')
print("DateTimeIndex...")
print(datetimeindex)
DateTimeIndex...
DatetimeIndex(['2021-12-30 02:30:50+10:30', '2021-12-31 02:30:50+10:30',
'2022-01-01 02:30:50+10:30', '2022-01-02 02:30:50+10:30',
'2022-01-03 02:30:50+10:30', '2022-01-04 02:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='D')
Using is_year_start Property
Now let's check which dates are the first day of the year ?
import pandas as pd
datetimeindex = pd.date_range('2021-12-30 02:30:50', periods=6, tz='Australia/Adelaide', freq='1D')
# Check which dates are first day of year
year_start_check = datetimeindex.is_year_start
print("Is year start check:")
print(year_start_check)
# Show corresponding dates
print("\nDates and their year start status:")
for date, is_start in zip(datetimeindex, year_start_check):
print(f"{date.strftime('%Y-%m-%d')}: {is_start}")
Is year start check: [False False True False False False] Dates and their year start status: 2021-12-30: False 2021-12-31: False 2022-01-01: True 2022-01-02: False 2022-01-03: False 2022-01-04: False
Multiple Year Start Example
Let's create an example with multiple year starts to see the pattern ?
import pandas as pd
# Create index with multiple January 1st dates
dates = ['2020-01-01', '2020-12-31', '2021-01-01', '2021-06-15', '2022-01-01']
datetimeindex = pd.DatetimeIndex(dates)
print("DateTimeIndex:")
print(datetimeindex)
print("\nYear start check:")
print(datetimeindex.is_year_start)
DateTimeIndex:
DatetimeIndex(['2020-01-01', '2020-12-31', '2021-01-01', '2021-06-15',
'2022-01-01'],
dtype='datetime64[ns]', freq=None)
Year start check:
[ True False True False True]
Return Value
The is_year_start property returns a numpy array of boolean values where:
-
Trueindicates the date is January 1st (first day of the year) -
Falseindicates the date is not January 1st
Conclusion
The is_year_start property provides a quick way to identify January 1st dates in a DateTimeIndex. It returns a boolean array that can be used for filtering or conditional operations on year-start dates.
