Reputation: 21
Does pandas (python) offer a way to easily get the current week of the month (1:4) from a date series?
data = {'date': ['2014-05-01', '2014-05-01', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-03', '2014-05-03', '2014-05-04', '2014-05-04']}
df = pd.DataFrame(data, columns = ['date'])
df['date']=pd.to_datetime(df['date'])
def week_of_month(dt):
""" Returns the week of the month for the specified date.
"""
first_day = dt.replace(day=1)
dom = dt.day
adjusted_dom = dom + first_day.weekday()
return int(ceil(adjusted_dom/7.0))
df ['week']=np.nan
for i in range(len(df)):
df ['week'][i] = week_of_month(df.date.iloc[i])
with a short data set it works but with a large data set takes to much resources
Upvotes: 0
Views: 2129
Reputation: 21
Problem solved:
data = {'date_x': ['2014-05-01', '2014-05-01', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-02', '2014-05-03', '2014-05-03', '2014-05-04', '2014-05-04']}
df = pd.DataFrame(data, columns = ['date_x'])
df['date']=pd.to_datetime(df['date_x'])
df['first_day_aux']=pd.to_datetime(df['date_x'][0][:8]+'01')
df['day']=df['date'].dt.day
df['adjusted_dom']=df['day']+df['first_day_aux'].dt.dayofweek
df['week']=np.int_(np.ceil(df['adjusted_dom']/7.0))
Upvotes: 2