深度阅读

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

作者
作者
2023年08月22日
更新时间
11.66 分钟
阅读时间
0
阅读量

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

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。