Question

I am trying to add a new column that converts the week column to be the appropriate month that the week is part of. If the week is split across 2 months then take the maximum month as the answer.

import pandas as pd

 data = {'Week': [201301, 201301, 201302, 201302, 201303],
'product': ['coke', 'fanta', 'coke' ,'sprite' ,'pepsi'],
'quantity': [1.5, 1.7, 3.6, 2.4, 2.9]}
 df = pd.DataFrame(data)

 print df
     Week product  quantity
0  201301    coke       1.5
1  201301   fanta       1.7
2  201302    coke       3.6
3  201306  sprite       2.4
4  201307   pepsi       2.9

so the output would look like this. any ideas?

   Week product     quantity   MonthMax
0  201301    coke       1.5       01
1  201301   fanta       1.7       01
2  201302    coke       3.6       01 
3  201305  sprite       2.4       02
4  201306   pepsi       2.9       02

even though week 201301 is part of dec12 and jan13 and also week 201305 is part of jan13 and feb13. The week format i am using by the way is yyyyww. I guess if I could just calculate the last day of that particular week and thus what the month is. but how can i do this in the easiest way. @alko

Was it helpful?

Solution

A possible way is to convert this last day of the week to a datetime, and then access the month of that:

df['LastDayWeek'] = pd.to_datetime((df['Week']-1).astype(str) + "6", format="%Y%U%w")

The minus one because python starts counting at zero (http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior), the + "6" is to have the last day of each week.
Then you get the month of these days with:

df['MonthMax'] = pd.DatetimeIndex(df['LastDayWeek']).month

gives:

In [6]: df
Out[6]:
     Week product  quantity         LastDayWeek  MonthMax
0  201301    coke       1.5 2013-01-05 00:00:00         1
1  201302   fanta       1.7 2013-01-12 00:00:00         1
2  201304    coke       3.6 2013-01-26 00:00:00         1
3  201306  sprite       2.4 2013-02-09 00:00:00         2
4  201308   pepsi       2.9 2013-02-23 00:00:00         2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top