Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if an object is a pandas datetime index?

Tags:

If I use type on a DataFrame which I know has a datetime index, I get:

In [17]: type(df.index) Out[17]: pandas.tseries.index.DatetimeIndex 

but when I test it, I get:

In [18]: type(df.index) == 'pandas.tseries.index.DatetimeIndex' Out[18]: False 

I know I assumed the type of type is a string, but I really don't know what else to try, and searching has resulted in nothing.

like image 740
piRSquared Avatar asked Jan 09 '14 20:01

piRSquared


People also ask

How do you check if an index exists in pandas?

contains() function return a boolean indicating whether the provided key is in the index. If the input value is present in the Index then it returns True else it returns False indicating that the input value is not present in the Index.

How do you identify a DataFrame index?

The get_loc() function is used to find the index of any column in the Python pandas dataframe. We simply pass the column name to get_loc() function to find index.

What is pandas datetime index?

DatetimeIndex. class pandas. DatetimeIndex [source] Immutable ndarray of datetime64 data, represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata such as frequency information.

What is a datetime object in pandas?

datetime object. Timestamp is the pandas equivalent of python's Datetime and is interchangeable with it in most cases. It's the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas.


2 Answers

You can use isinstance of the DatetimeIndex class:

In [11]: dates = pd.date_range('20130101', periods=6)  In [12]: dates Out[12]:  <class 'pandas.tseries.index.DatetimeIndex'> [2013-01-01 00:00:00, ..., 2013-01-06 00:00:00] Length: 6, Freq: D, Timezone: None  In [13]: isinstance(dates, pd.DatetimeIndex) Out[13]: True 
like image 77
Andy Hayden Avatar answered Sep 17 '22 08:09

Andy Hayden


What did you import Pandas as?

If you are following the guide in the documentation and did something like:

import pandas as pd dates = pd.date_range('20130101', periods=6)  type(dates[0])  pandas.tslib.TimestampTimestamp('2013-01-01 00:00:00', tz=None)  type(dates[0]) == pandas.tslib.Timestamp False   # this throws NameError since you didn't import as pandas  type(dates[0]) == pd.tslib.Timestamp True   # this works because we imported Pandas as pd 

Out of habit I neglected to mention as @M4rtini highlighted that you should not be using a string to compare equivalency.

like image 36
Matthew Avatar answered Sep 20 '22 08:09

Matthew