Python 将日期/时间拆分为期间的If语句
只是一个小背景故事,我需要创建一个修改过的专栏,名为“分析期”,将36个月的周期划分为3个区间。例如,(2014年5月至2015年4月),(2015年5月至2016年4月)和(2016年5月至2017年4月)。这将与我们的本地工具一起使用 我能够用下面的代码完成这项壮举,但是我想知道是否有一种更有效的方法可以做到这一点,而不必手动更新日期范围。 同样关于下面的if语句,最初我尝试用一个if语句和两个对应的elif语句。然而,这似乎并不奏效。有人能解释一下原因吗 多谢各位Python 将日期/时间拆分为期间的If语句,python,pandas,numpy,Python,Pandas,Numpy,只是一个小背景故事,我需要创建一个修改过的专栏,名为“分析期”,将36个月的周期划分为3个区间。例如,(2014年5月至2015年4月),(2015年5月至2016年4月)和(2016年5月至2017年4月)。这将与我们的本地工具一起使用 我能够用下面的代码完成这项壮举,但是我想知道是否有一种更有效的方法可以做到这一点,而不必手动更新日期范围。 同样关于下面的if语句,最初我尝试用一个if语句和两个对应的elif语句。然而,这似乎并不奏效。有人能解释一下原因吗 多谢各位 date_time={'
date_time={'Date_Fields':[datetime.date(2014,5,1),datetime.date(2015,5,1),datetime.date(2016,5,1),datetime.date(2018,5,1)]}
date_time=pd.DataFrame(date_time)
date_time["Analysis Period"]=""
if((日期时间[“日期字段”]>=datetime.date(2014,5,1))&(日期时间[“日期字段”]=datetime.date(2014,5,1))&(日期时间[“日期字段”]=datetime.date(2015,5,1))&(日期时间[“日期字段”]=datetime.date(2015,5,1))&(日期时间[“日期字段”]=datetime.datetime(2016,5,1))&(日期时间[“日期字段”]=datetime(2016,5,1))[“日期字段”]设置
考虑数据文件<代码>日期/时间>代码> < /P>
if ((date_time["Date_Fields"]>= datetime.date(2014,5,1)) & (date_time["Date_Fields"]<=datetime.date(2015,4,30))) is not False:
date_time["Analysis Period"]=np.where(((date_time["Date_Fields"]>= datetime.date(2014,5,1)) & (date_time["Date_Fields"]<=datetime.date(2015,4,30))),'May 2014 to April 2015', date_time["Analysis Period"])
if ((date_time["Date_Fields"]>= datetime.date(2015,5,1)) & (date_time["Date_Fields"]<=datetime.date(2016,4,30))) is not False:
date_time["Analysis Period"]=np.where(((date_time["Date_Fields"]>= datetime.date(2015,5,1)) & (date_time["Date_Fields"]<=datetime.date(2016,4,30))),'May 2015 to April 2016', date_time["Analysis Period"])
if ((date_time["Date_Fields"]>= datetime.date(2016,5,1)) & (date_time["Date_Fields"]<=datetime.date(2017,4,30))) is not False:
date_time["Analysis Period"]=np.where(((date_time["Date_Fields"]>= datetime.date(2016,5,1)) & (date_time["Date_Fields"]<=datetime.date(2017,4,30))),'May 2016 to April 2017',date_time["Analysis Period"])
解决方案
使用pd.Series.dt.to_period
和freq='A-Apr
指定在4月份结束的年度期间
date_time = pd.DataFrame(dict(
Date_Fields=pd.date_range('2014-05-01', periods=12, freq='Q'),
Other_Field=np.arange(12)
))
Date_Fields Other_Field
0 2014-06-30 0
1 2014-09-30 1
2 2014-12-31 2
3 2015-03-31 3
4 2015-06-30 4
5 2015-09-30 5
6 2015-12-31 6
7 2016-03-31 7
8 2016-06-30 8
9 2016-09-30 9
10 2016-12-31 10
11 2017-03-31 11
您需要pd.cut()
。谢谢您,我们会仔细阅读。非常好的解决方案!
date_time.assign(**{
'Analysis Period': date_time.Date_Fields.dt.to_period('A-Apr')
})
Date_Fields Other_Field Analysis Period
0 2014-06-30 0 2015
1 2014-09-30 1 2015
2 2014-12-31 2 2015
3 2015-03-31 3 2015
4 2015-06-30 4 2016
5 2015-09-30 5 2016
6 2015-12-31 6 2016
7 2016-03-31 7 2016
8 2016-06-30 8 2017
9 2016-09-30 9 2017
10 2016-12-31 10 2017
11 2017-03-31 11 2017