2

I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')

Is there a more efficient way of doing this?

coding_monkey
  • 397
  • 7
  • 18
  • maybe this post will help you: https://stackoverflow.com/questions/2803852/python-date-string-to-date-object – Green Dec 04 '17 at 07:24

2 Answers2

3

Use to_datetime:

df['DWY'] = pd.to_datetime(df['DWY'],format='%w-%U-%Y')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

You could use the map function:

df['DWY'] = list(map(lambda x: dt.strptime(x,'%w-%U-%Y'), df['DWY']))

I personally like the way list comprehension work better:

df['DWY'] = [dt.strptime(entry, '%w-%U-%Y') for entry in df['DWY']]
Arne
  • 17,706
  • 5
  • 83
  • 99