📅  最后修改于: 2023-12-03 15:19:15.583000             🧑  作者: Mango
Series.dt.weekday
is a pandas function that is used to extract the week day number of the datetime in a Series.
Series.dt.weekday
This function does not take any parameters.
This function returns an integer value corresponding to the week day number of the datetime in a Series. The weekday number starts from 0, which represents Monday and ends at 6, which represents Sunday.
import pandas as pd
data = {'date': ['2022-02-01', '2022-02-02', '2022-02-03', '2022-02-04', '2022-02-05', '2022-02-06', '2022-02-07']}
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
df['weekday'] = df['date'].dt.weekday
print(df)
Output:
date weekday
0 2022-02-01 1
1 2022-02-02 2
2 2022-02-03 3
3 2022-02-04 4
4 2022-02-05 5
5 2022-02-06 6
6 2022-02-07 0
In this example, we have created a pandas DataFrame with a date column, and then converted it to a datetime format using pd.to_datetime
function. Then, we have used Series.dt.weekday
function to extract the week day numbers corresponding to each date in the date column, and have added the values to a new column called weekday.
Note that the week day numbers are 1-based in this example, i.e., Monday is represented by 1 instead of 0. This is because the default value of Series.dt.weekday
function is 0
for Monday, 1
for Tuesday, and so on. To convert the week day numbers to 0-based format, we can subtract 1
from the result.
df['weekday'] = df['date'].dt.weekday - 1
print(df)
Output:
date weekday
0 2022-02-01 0
1 2022-02-02 1
2 2022-02-03 2
3 2022-02-04 3
4 2022-02-05 4
5 2022-02-06 5
6 2022-02-07 6