我创建了一个日期数据框,如下所示:
import pandas as pd
timespan = 366
df = pd.DataFrame({'Date':pd.date_range(pd.datetime.today(), periods=timespan).tolist()})
我很难确定一个季度的日期数字。例如
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
我可以提出你的建议吗?提前谢谢。
答案 0 :(得分:3)
>>> df.assign(
days_in_qurater=[(date - ts.start_time).days + 1
for date, ts in zip(df['Date'],
pd.PeriodIndex(df['Date'], freq='Q'))])
Date days_in_qurater
0 2017-01-01 1
1 2017-01-02 2
2 2017-01-03 3
...
363 2017-12-30 91
364 2017-12-31 92
365 2018-01-01 1
答案 1 :(得分:1)
其中一种方法是根据日期和季度cumcount创建一个新的df,然后将值映射到真正的df,即
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()))
映射值
df['expected'] = df.Date.dt.date.map(maps)
输出:
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
希望它有所帮助。
答案 2 :(得分:0)
从:
开始day_of_year = datetime.now().timetuple().tm_yday
这 Convert Year/Month/Day to Day of Year in Python
你可以通过这种方式获得每个季度的第一天,并且可以减去第一天的价值以获得该季度的那一天
答案 3 :(得分:0)
这比Alexander's solution快250倍:
df['day_qtr']=(df.Date - pd.PeriodIndex(df.Date,freq='Q').start_time).dt.days + 1