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
Display all the Sundays of a given year using Pandas in Python
Pandas is a powerful Python library for data manipulation and analysis. One of its key features is the ability to handle date and time data effectively. In this article, we will show you how to use Pandas to display all the Sundays of a given year using different approaches.
Prerequisites
Before we start, make sure you have Pandas installed on your machine. You can install it by running the following command in your terminal ?
pip install pandas
Method 1: Using day_name() Function
The first approach uses the day_name() method to identify Sundays by their name.
Step-by-Step Implementation
First, let's create a date range for the entire year and filter for Sundays ?
import pandas as pd
# Define the year
year = 2023
# Create date range for the entire year
start_date = f'{year}-01-01'
end_date = f'{year}-12-31'
dates = pd.date_range(start_date, end_date)
# Filter for Sundays using day_name()
sundays = dates[dates.day_name() == 'Sunday']
# Display the first 5 Sundays
print("First 5 Sundays of", year)
for i, sunday in enumerate(sundays[:5]):
print(sunday.strftime('%Y-%m-%d (%A)'))
First 5 Sundays of 2023 2023-01-01 (Sunday) 2023-01-08 (Sunday) 2023-01-15 (Sunday) 2023-01-22 (Sunday) 2023-01-29 (Sunday)
Method 2: Using weekday Attribute
The second approach uses the weekday attribute where Sunday is represented by 6 (Monday=0, Sunday=6) ?
import pandas as pd
# Create date range for 2023
date_range = pd.date_range(start='2023-01-01', end='2023-12-31')
# Filter for Sundays (weekday == 6)
sundays = date_range[date_range.weekday == 6]
print(f"Total Sundays in 2023: {len(sundays)}")
print("\nFirst 3 and last 3 Sundays:")
print(sundays[:3].strftime('%Y-%m-%d').tolist())
print("...")
print(sundays[-3:].strftime('%Y-%m-%d').tolist())
Total Sundays in 2023: 53 First 3 and last 3 Sundays: ['2023-01-01', '2023-01-08', '2023-01-15'] ... ['2023-12-17', '2023-12-24', '2023-12-31']
Creating a DataFrame for Better Display
For better visualization, we can create a DataFrame with additional information ?
import pandas as pd
# Get all Sundays for 2023
year = 2023
dates = pd.date_range(start=f'{year}-01-01', end=f'{year}-12-31')
sundays = dates[dates.day_name() == 'Sunday']
# Create a DataFrame with additional information
sunday_df = pd.DataFrame({
'Date': sundays,
'Month': sundays.month_name(),
'Day_of_Year': sundays.dayofyear,
'Week_of_Year': sundays.isocalendar().week
})
print(sunday_df.head(8))
Date Month Day_of_Year Week_of_Year
0 2023-01-01 January 1 1
1 2023-01-08 January 8 2
2 2023-01-15 January 15 3
3 2023-01-22 January 22 4
4 2023-01-29 January 29 5
5 2023-02-05 February 36 6
6 2023-02-12 February 43 7
7 2023-02-19 February 50 8
Complete Function for Any Year
Here's a reusable function that displays all Sundays for any given year ?
import pandas as pd
def get_sundays_of_year(year):
"""
Returns all Sundays of a given year as a DataFrame
"""
# Create date range for the year
dates = pd.date_range(start=f'{year}-01-01', end=f'{year}-12-31')
# Filter for Sundays
sundays = dates[dates.day_name() == 'Sunday']
# Create DataFrame with details
sunday_df = pd.DataFrame({
'Date': sundays.strftime('%Y-%m-%d'),
'Month': sundays.month_name(),
'Quarter': sundays.quarter
})
return sunday_df
# Test the function
result = get_sundays_of_year(2024)
print(f"Sundays in 2024: {len(result)}")
print(result.head())
Sundays in 2024: 52
Date Month Quarter
0 2024-01-07 January 1
1 2024-01-14 January 1
2 2024-01-21 January 1
3 2024-01-28 January 1
4 2024-02-04 February 1
Comparison of Methods
| Method | Syntax | Readability | Performance |
|---|---|---|---|
day_name() == 'Sunday' |
More intuitive | High | Slower |
weekday == 6 |
More concise | Medium | Faster |
Conclusion
Pandas provides multiple ways to extract Sundays from a year using day_name() or weekday attributes. The day_name() method is more readable while weekday is more efficient for large datasets. Both approaches effectively help in date filtering and analysis tasks.
