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 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.

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

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.

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 code 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:

Example: Convert a pandas date to week number

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.