Home > Mobile >  Calculating day of week from month, year and day and adding it as a column in my dataset
Calculating day of week from month, year and day and adding it as a column in my dataset

Time:08-19

I have dataset as below: enter image description here

I tried to calculate the day of the week using year, month and day, but got error as follows:

enter image description here

enter image description here 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
  • Related