I tried to calculate the day of the week using year, month and day, but got error as follows:
Can someone please help me out to code this?
CodePudding user response:
You can use pandas.Series.dt.day_name
.
import datetime
import pandas as pd
df = pd.DataFrame({'date': [datetime.datetime(2021,1,1),
datetime.datetime(2021,4,1),
datetime.datetime(2021,5,1),
datetime.datetime(2022,3,1),
datetime.datetime(2022,3,31)
]})
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
Method 1: using the datetime values.
df['date'].dt.day_name()
>>>
0 Friday
1 Thursday
2 Saturday
3 Tuesday
4 Thursday
Name: date, dtype: object
Method 2: using the year, month, and day values.
pd.to_datetime(df[['year', 'month', 'day']]).dt.day_name()
>>>
0 Friday
1 Thursday
2 Saturday
3 Tuesday
4 Thursday
dtype: object