我正在尝试检查我的开始日期和结束日期是否在我的数据框中的给定StartDate和EndDate之间
DataFrame看起来像
TermYear Term StartDate EndDate
2017 1 2017-01-10 2017-03-31
2017 2 2017-04-10 2017-06-30
2017 3 2017-07-24 2017-09-18
2017 4 2017-09-30 2017-12-04
我想在我的指定日期
时获取术语和TermYearStart Date: '2017-01-24'
End Date: '2017-09-29'
在数据帧的开始和结束日期之间是否应该获取多行任何想法? 我试过了
lowerDate = np.datetime64('2017-07-24')
upperDate = np.datetime64('2017-07-26')
termDates = termDates[(termDates.StartDate >= lowerDate) &
(termDates.EndDate <= upperDate) ][['Term', 'TermYear']]
但它返回空数据框
预期产出:
Term TermYear
2017 1
2017 2
2017 3
答案 0 :(得分:2)
使用
In [1820]: df[(df.StartDate <= StartDate) & (df.EndDate >= EndDate)]
Out[1820]:
TermYear Term StartDate EndDate
2 2017 3 2017-07-24 2017-09-18
对于特定列
In [1826]: df.loc[(df.StartDate<=StartDate) & (df.EndDate>=EndDate), ['Term', 'TermYear']]
Out[1826]:
Term TermYear
2 3 2017
其中,
In [1821]: df
Out[1821]:
TermYear Term StartDate EndDate
0 2017 1 2017-01-10 2017-03-31
1 2017 2 2017-04-10 2017-06-30
2 2017 3 2017-07-24 2017-09-18
3 2017 4 2017-09-30 2017-12-04
In [1822]: StartDate
Out[1822]: '2017-07-24'
In [1823]: EndDate
Out[1823]: '2017-08-29'
In [1835]: df.dtypes
Out[1835]:
TermYear int64
Term int64
StartDate datetime64[ns]
EndDate datetime64[ns]
dtype: object