Date feature extraction helps us get useful parts from dates, like year or month, to understand patterns in data better.
0
0
Date feature extraction in Data Analysis Python
Introduction
You want to find sales trends by month or day.
You need to group data by weekdays or weekends.
You want to see if events happen more in certain years.
You want to add new columns like hour or quarter from timestamps.
Syntax
Data Analysis Python
df['new_feature'] = df['date_column'].dt.feature_name
Use .dt to access date parts from a pandas datetime column.
Common features: year, month, day, weekday, hour, quarter.
Examples
Extracts the year from the date column.
Data Analysis Python
df['year'] = df['date'].dt.year
Extracts the month number (1-12) from the date column.
Data Analysis Python
df['month'] = df['date'].dt.month
Extracts the weekday as a number (Monday=0, Sunday=6).
Data Analysis Python
df['weekday'] = df['date'].dt.weekday
Extracts the quarter of the year (1 to 4).
Data Analysis Python
df['quarter'] = df['date'].dt.quarter
Sample Program
This code creates a table with dates, converts them to date type, then adds new columns for year, month, weekday, and quarter.
Data Analysis Python
import pandas as pd # Create sample data with dates data = {'date': ['2023-01-15', '2023-04-20', '2023-07-10', '2023-10-05']} df = pd.DataFrame(data) # Convert 'date' column to datetime type df['date'] = pd.to_datetime(df['date']) # Extract year, month, weekday, and quarter df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month df['weekday'] = df['date'].dt.weekday df['quarter'] = df['date'].dt.quarter print(df)
OutputSuccess
Important Notes
Make sure your date column is in datetime format before extracting features.
Weekday numbers start at 0 for Monday, which helps in grouping by weekdays.
Quarter divides the year into four parts: Jan-Mar (1), Apr-Jun (2), Jul-Sep (3), Oct-Dec (4).
Summary
Date feature extraction breaks down dates into parts like year, month, and day.
It helps find patterns and group data by time periods.
Use pandas .dt accessor to get these features easily.