[英]Resampling Pandas Timeseries so that the Date indicated the 1st of each Month
[英]How do I offset Pandas dayofyear so start date is 1st October not 1st January?
我有以下数据框:
我如何抵消 Pandas dayofyear 所以开始日期是 10 月 1 日而不是 1 月 1 日
在这种情况下,我希望年份是从 10 月 1 日到 9 月 30 日,并且需要考虑闰年。
下面是我想要输出的示例,年份列是唯一的变量。
这是表格形式的数据框:
Day stock dayofyear weekday month year leapyear
0 24/09/2019 10 267 1 9 2019 False
1 25/09/2019 10 268 2 9 2019 False
2 26/09/2019 11 269 3 9 2019 False
3 27/09/2019 12 270 4 9 2019 False
4 28/09/2019 14 271 5 9 2019 False
5 29/09/2019 14 272 6 9 2019 False
6 30/09/2019 15 273 0 9 2019 False
7 01/10/2019 16 274 1 10 2019 False
8 02/10/2019 17 275 2 10 2019 False
9 03/10/2019 18 276 3 10 2019 False
10 04/10/2019 19 277 4 10 2019 False
用:
df['Day'] = pd.to_datetime(df['Day'], dayfirst=True)
base_year = np.where(df['month'].ge(10), df['year'], df['year'].sub(1))
base_date = pd.to_datetime(base_year, format='%Y') + pd.DateOffset(months=9)
df['dayofyear'] = (df['Day'] - base_date).dt.days.add(1)
细节:
使用pd.to_datetime
将Day
列转换为 pandas 日期时间系列,然后使用np.where
以及Series.gt
和Series.sub
来计算Day
列中每个日期的base_year
。
print(base_year)
array([2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019])
使用pd.to_datetime
的转换base_year
到大熊猫的datetime系列,并添加一个偏移的9 months
使得base_date
从开始1 October
。
print(base_date)
DatetimeIndex(['2018-10-01', '2018-10-01', '2018-10-01', '2018-10-01',
'2018-10-01', '2018-10-01', '2018-10-01', '2019-10-01',
'2019-10-01', '2019-10-01', '2019-10-01'],
dtype='datetime64[ns]', freq=None)
从此base_date
减去Day
列并使用Series.dt.days
计算dayofyear
:
print(df)
Day stock dayofyear weekday month year leapyear
0 2019-09-24 10 359 1 9 2019 False
1 2019-09-25 10 360 2 9 2019 False
2 2019-09-26 11 361 3 9 2019 False
3 2019-09-27 12 362 4 9 2019 False
4 2019-09-28 14 363 5 9 2019 False
5 2019-09-29 14 364 6 9 2019 False
6 2019-09-30 15 365 0 9 2019 False
7 2019-10-01 16 1 1 10 2019 False
8 2019-10-02 17 2 2 10 2019 False
9 2019-10-03 18 3 3 10 2019 False
10 2019-10-04 19 4 4 10 2019 False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.