How to extract the day of the week from a date column in a Pandas DataFrame?

Published on Aug. 22, 2023, 12:19 p.m.

To extract the day of the week from a date column in a Pandas DataFrame, you can use the dt.dayofweek method. Here is an example:

import pandas as pd

# Create a sample DataFrame with a column of dates
data = {'date': ['2022-03-05', '2022-03-06', '2022-03-07']}
df = pd.DataFrame(data)

# Convert the 'date' column to datetime format
df['date'] = pd.to_datetime(df['date'])

# Extract the day of the week from the 'date' column
df['day_of_week'] = df['date'].dt.dayofweek

# Print the updated DataFrame
print(df)

This code will output the following DataFrame with a new ‘day_of_week’ column containing the extracted day of the week as an integer (Monday=0, Sunday=6):

date  day_of_week
0 2022-03-05            5
1 2022-03-06            6
2 2022-03-07            0

You can also use the dt.day_name() method to extract the day of the week as a string:

df['day_name'] = df['date'].dt.day_name()

This will output the following DataFrame with a new ‘day_name’ column containing the name of the day of the week:

date day_of_week   day_name
0 2022-03-05     Saturday
1 2022-03-06       Sunday
2 2022-03-07       Monday

Tags: