11
# pseudo code: 
myPeriod.contains(myTimestamp)

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

YunliuStorage
  • 479
  • 5
  • 14

2 Answers2

11

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
maxymoo
  • 35,286
  • 11
  • 92
  • 119
  • 3
    Thank you, but I expected something more concise, considering this is python, and we are using pandas on top of python. – YunliuStorage Mar 07 '16 at 22:07
  • 1
    in my opinion this is fairly concise and pythonic, most languages won't let you combine a double inequality like this – maxymoo Mar 10 '16 at 00:49
  • 1
    Oh nice, I did not know that (the double inequality thing) was possible in python, I thought that was a pseudo code. Thanks. – YunliuStorage Mar 14 '16 at 14:43
8

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]
Community
  • 1
  • 1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thank you for such prompt reply, I knew I was missing something. But since we are here, I have one further question: How do I make myself aware of the existence of "isin"? It is not in Pandas webpage "Time Series / Date functionality" – YunliuStorage Mar 07 '16 at 22:07
  • You can find it in [Indexing and Selecting Data](http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-with-isin) – jezrael Mar 07 '16 at 22:14
  • this isn't really about `isin`, the essence of your answer is converting the timestamp to a period and checking for equality, what's realling going on is the expression `myTimestamp.to_period(myPeriod.freqstr) == myPeriod` – maxymoo Mar 07 '16 at 22:33
  • if out of the context manipulation of indexes, I will just use your earlier : myPeriod.start_time < myTimestamp < myPeriod.end_time, I figure it would be faster and more readable. Obviously I was hoping for a 'Timestamp in Period' – YunliuStorage Mar 08 '16 at 23:22