我正在尝试为日期实现等效的numpy.where
,如下所示:
from datetime import date, timedelta as td, datetime
d1 = datetime.strptime('1/1/1995', "%m/%d/%Y")
d2 = datetime.strptime('12/31/2015', "%m/%d/%Y")
AllDays = []
while(d1<=d2):
AllDays.append(d1)
d1 = d1 + td(days=1)
validDate = AllDays
trainStDt = '1/1/1995'
trainEnDt = '12/31/2013'
testStDt = '1/1/2014'
testEnDt = '12/31/2015'
indTrain = (validDate >= datetime.strptime(trainStDt,'%m/%d/%Y')) & (validDate <=
datetime.strptime(trainEnDt,'%m/%d/%Y'))
indTest = (validDate >= datetime.strptime(testStDt,'%m/%d/%Y')) & (validDate <=
datetime.strptime(testEnDt,'%m/%d/%Y'))
trainDates = validDate[indTrain]
testDates = validDate[indTest]
print trainDates[0]
print trainDates[-1:]
print testDates[0]
print testDates[-1:]
然而: (1)indTrain没有工作,因为它试图将列表与日期时间进行比较 (2)我的解决方案是循环遍历validDates的每个元素
有更好的方法吗?
答案 0 :(得分:1)
只需将列表转换为数组即可。将import numpy as np
添加到脚本顶部,然后在while
循环后添加:
AllDays = np.array(AllDays)