day number of a quarter for a given date in pandas

i have create a data frame of date as follows:

import pandas as pd

timespan = 366
df = pd.DataFrame({'Date':pd.date_range(pd.datetime.today(), periods=timespan).tolist()})

i’m struggling to identify the day number in a quarter. For example

date          expected_value
2017-01-01       1           # because it it the first day in Q1
2017-01-02       2           # because it is the second day in Q1
2017-02-01      32           # because it is the 32th day in Q1
2017-04-01       1           # because it is the first day in Q2

May I have your suggestions? Thank you in advance.

Answer

One of way is by creating a new df based on dates and quarter cumcount then map the values to the real df i.e

timespan = 5000
ndf = pd.DataFrame({'Date':pd.date_range('2015-01-01', periods=timespan).tolist()})
ndf['q'] = ndf['Date'].dt.to_period('Q')
ndf['new'] = ndf.groupby('q').cumcount()+1
maps = dict(zip(ndf['Date'].dt.date, ndf['new'].values.tolist()))

Map the values

df['expected'] = df.Date.dt.date.map(maps)

Output:

                       Date  expected
0 2017-09-12 09:42:14.324492        74
1 2017-09-13 09:42:14.324492        75
2 2017-09-14 09:42:14.324492        76
3 2017-09-15 09:42:14.324492        77
4 2017-09-16 09:42:14.324492        78
.
.
143 2018-02-02 09:42:14.324492        33
.
.
201 2018-04-01 09:42:14.324492         1

Hope it helps.