Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a pandas.Timestamp is in a pandas.Period

# pseudo code: 
myPeriod.contains(myTimestamp)

I found the lack of such function in pandas quite surprising. Am I missing something here?

like image 943
YunliuStorage Avatar asked Mar 07 '16 21:03

YunliuStorage


2 Answers

You can access the boundaries of a period with start_time and end_time, hence the expression for whether a time is within a period would would be

myPeriod.start_time < myTimestamp < myPeriod.end_time
like image 101
maxymoo Avatar answered Oct 15 '22 10:10

maxymoo


You can try isin if you have multiple values:

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]

If you want compare only one datetime, easier is use (thanks maxymoo):

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]  

Or with 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]
like image 31
jezrael Avatar answered Oct 15 '22 10:10

jezrael