Converting a pandas date to week number

Given a Pandas DataFrame, we have to convert a pandas date to week number.
Submitted by Pranit Sharma, on July 23, 2022

Pandas DataFrame

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.

Python Datetime Library

Datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually, date is present in the format of 'yy-mm-dd' and time is present in the format of 'HH:MM:SS'.

Here,

  • yy means year
  • mm means month
  • dd means day
  • HH means hours
  • MM means minutes
  • SS means seconds

Converting a pandas date to week number

To convert a pandas date to a week number, we will use .dt().isocalender() method which has an attribute called week, it will return the week number of the particular data which is passed inside it.

Note

To work with pandas, we need to import pandas package first, below is the syntax:

import pandas as pd

Let us understand with the help of an example,

Python program to convert a pandas date to week number

# Importing pandas package
import pandas as pd

# Creating a Dictionary
d = {
    'col1':[12,24,36,48,60],
    'col2':[13,26,39,52,65],
    'Date':['2015-06-12','2015-08-02','2011-04-11','2014-09-23','2012-05-30']
}

# Creating a DataFrame
df = pd.DataFrame(d)

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

# Converting values of Data column in datetime
df['Date'] = pd.to_datetime(df['Date'])

# Getting week value
df['Week'] = df['Date'].dt.isocalendar().week

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

Output

The output of the above program is:

Example: Convert a pandas date to week number

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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