user308827
user308827

Reputation: 21961

Asserting that pandas dataframe has a datetime index through decorator

How can I add a decorator stating that the incoming pandas dataframe argument to a function has a datetime index?

I have looked at the packages engarde and validada, but not found anything yet. I could do this check inside the function, but would prefer a decorator.

Upvotes: 4

Views: 2078

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

As @PadraicCunningham writes, it is not too hard to create one using functools.wraps:

import functools

def assert_index_datetime(f):
    @functools.wraps(f)
    def wrapper(df):
        assert df.index.dtype == pd.to_datetime(['2013']).dtype
        return f(df)
    return wrapper

@assert_index_datetime
def fn(df):
    pass

df = pd.DataFrame({'a': [1]}, index=pd.to_datetime(['2013']))
fn(df)

Upvotes: 5

chrisb
chrisb

Reputation: 52236

Here's one, somewhat patterned off of engarde

In [84]: def has_datetimeindex(func):
    ...:     @wraps(func)
    ...:     def wrapper(df, *args, **kwargs):
    ...:         assert isinstance(df.index, pd.DatetimeIndex)
    ...:         return func(df, *args, **kwargs)
    ...:     return wrapper

In [85]: @has_datetimeindex
    ...: def f(df):
    ...:     return df + 1

In [86]: df = pd.DataFrame({'a':[1,2,3]})

In [87]: f(df)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-87-ce83b19059ea> in <module>()
----> 1 f(df)

<ipython-input-84-1ecf9973e7d5> in wrapper(df, *args, **kwargs)
      2     @wraps(func)
      3     def wrapper(df, *args, **kwargs):
----> 4         assert isinstance(df.index, pd.DatetimeIndex)
      5         return func(df, *args, **kwargs)
      6     return wrapper

AssertionError: 

In [88]: df = pd.DataFrame({'a':[1,2,3]}, index=pd.date_range('2014-1-1', periods=3))

In [89]: f(df)
Out[89]: 
            a
2014-01-01  2
2014-01-02  3
2014-01-03  4

Upvotes: 2

Related Questions