检查 pandas.Timestamp 是否在 pandas.Period 中
Check if a pandas.Timestamp is in a pandas.Period
# pseudo code:
myPeriod.contains(myTimestamp)
我发现 pandas 中缺少这样的功能非常令人惊讶。我在这里遗漏了什么吗?
您可以使用 start_time
和 end_time
访问时间段的边界,因此表示时间是否在时间段内的表达式将是
myPeriod.start_time < myTimestamp < myPeriod.end_time
如果您有多个值,您可以尝试isin
:
print df.index
PeriodIndex(['2015-11'], dtype='int64', name=u'', freq='M')
d = "2015-09-01"
d1 = "2015-10-01"
print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
[False]
d = "2015-11-01"
d1 = "2015-11-01"
print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
[ True]
如果你只想比较一个 datetime
,使用起来更容易(感谢 ):
d = "2015-09-01"
print df.index == pd.to_datetime(d).to_period('M')
[False]
d = "2015-11-01"
print df.index == pd.to_datetime(d).to_period('M')
[True]
或 Series
:
print df.a
0 2015-11
Name: a, dtype: object
d = "2015-09-01"
d1 = "2015-10-01"
print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
[False]
d = "2015-11-01"
d1 = "2015-11-01"
print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
[ True]
# pseudo code:
myPeriod.contains(myTimestamp)
我发现 pandas 中缺少这样的功能非常令人惊讶。我在这里遗漏了什么吗?
您可以使用 start_time
和 end_time
访问时间段的边界,因此表示时间是否在时间段内的表达式将是
myPeriod.start_time < myTimestamp < myPeriod.end_time
如果您有多个值,您可以尝试isin
:
print df.index
PeriodIndex(['2015-11'], dtype='int64', name=u'', freq='M')
d = "2015-09-01"
d1 = "2015-10-01"
print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
[False]
d = "2015-11-01"
d1 = "2015-11-01"
print df.index.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')])
[ True]
如果你只想比较一个 datetime
,使用起来更容易(感谢
d = "2015-09-01"
print df.index == pd.to_datetime(d).to_period('M')
[False]
d = "2015-11-01"
print df.index == pd.to_datetime(d).to_period('M')
[True]
或 Series
:
print df.a
0 2015-11
Name: a, dtype: object
d = "2015-09-01"
d1 = "2015-10-01"
print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
[False]
d = "2015-11-01"
d1 = "2015-11-01"
print df.a.isin([pd.to_datetime(d).to_period('M'), pd.to_datetime(d1).to_period('M')]).values
[ True]