John
John

Reputation: 349

To get the week number in a column using Python

I was trying to get this requirement where I want to have a column in my dataframe with week number, based on Days, Month an yr present in data. Here is the below code-

import pandas as pd
import numpy as np
s={'yr':[2014,2014,2014,2014,2015,2015,2015,2015],'Month':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug'],'Days':[12,24,11,22,10,15,22,3]}
p=pd.DataFrame(data=s)

enter image description here

import datetime
p['week']=datetime.date(p['yr'], p['Month'], p['Days']).isocalendar().week

I am getting the below error-
TypeError: cannot convert the series to <class 'int'>

I am not sure on how to resolve this error, I think I need to convert Month in numeric format too, how would be able to do this and get the week number in the date also?

Upvotes: 0

Views: 323

Answers (1)

Ukulele
Ukulele

Reputation: 695

This line isn't as nice, but it works:

p['week'] = [datetime.datetime.strptime(str(p['yr'][i])+p['Month'][i]+str(p['Days'][i]), '%Y%b%d').isocalendar()[1] for i in range(len(p))]

Upvotes: 1

Related Questions