Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to check if Pandas DataFrame index is a certain type (DatetimeIndex)

Tags:

python

pandas

In the code below I want to check if the index in the dataframes is of type DatetimeIndex. Is this a correct way of doing this? Is there a better way to do this than with the if statement? It seems straight-forward, but wonder if I'm missing something.

I want to do this because I foresee that users occassionally may not read in the data with the corresponding date information.

import pandas as pd
data = {'x' : [1,2,3],
    'y' : [4,5,6]}

index = pd.date_range("2014-1-1", periods=3, freq="D")

Case 1

df = pd.DataFrame(data)
type(df.index) == pd.tseries.index.DatetimeIndex

Correctly returns: False

Case 2

df = pd.DataFrame(data, index=index)
type(df.index) == pd.tseries.index.DatetimeIndex

Correctly returns: True

Thanks in advance. And I hope that this isn't too trivial.

like image 460
dpk Avatar asked Jul 30 '14 17:07

dpk


People also ask

How do you check pandas Dtype?

To check the data type in pandas DataFrame we can use the “dtype” attribute. The attribute returns a series with the data type of each column. And the column names of the DataFrame are represented as the index of the resultant series object and the corresponding data types are returned as values of the series object.

What is the data type of index in pandas?

Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects. Pandas Index.

What is DatetimeIndex pandas?

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.

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.


1 Answers

As of 2021, here is the up to date way of checking this:

>>> df.index.inferred_type == "datetime64"
>>> True

So you could add something like this into your application:

assert df.index.inferred_type == 'datetime64', "must have a datetime index"

Cheers

like image 51
binarymason Avatar answered Sep 21 '22 03:09

binarymason