Get week start date (Monday) from a date column in Pandas?

Learn, how to get week start date (Monday) from a date column in Python Pandas?
Submitted by Pranit Sharma, on December 01, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given the data frame where we have a column called 'day' which is of DateTime type. Now since it is of DateTime type it must have the date and time values in it. We need to process the data part of each of these values and find the start date of the week according to the date.

Getting week start date (Monday) from a date column

For this purpose, we will first convert the column to the period where we will pass the parameter 'w' which means week and we will apply the lambda function where we will pass the start time value to each value of the column.

Let us understand with the help of an example,

Python program to get week start date (Monday) from a date column in Pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({
    'Name':['Ram','Shyam','Seeta','Geeta'],
    'Admission':[2023,4043,1234,4738],
    'DOB':['2002/01/01','2002/10/01','2002/05/03','2002/01/07']
})

# Display Original df
print("Original DataFrame:\n",df,"\n")

# Converting DOB column to datetime
df['DOB'] = pd.to_datetime(df['DOB'])

# getting start date of week
res = df['DOB'].dt.to_period('W').apply(lambda r: r.start_time)

# Display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Get week start date (Monday) from a date column in Pandas?

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.