Python 通过decorator断言pandas dataframe具有datetime索引

Python 通过decorator断言pandas dataframe具有datetime索引,python,pandas,decorator,datetimeindex,Python,Pandas,Decorator,Datetimeindex,如何添加一个装饰器,声明函数的传入dataframe参数具有datetime索引 我已经看过engarde和validada的包装,但还没有找到任何东西。我可以在函数内部执行此检查,但更喜欢装饰器。这里有一个,有点像 [84]中的:def具有_datetimeindex(func): …:@wrapps(func) …:def包装(df、*args、**kwargs): …:断言isinstance(df.index,pd.DatetimeIndex) …:返回函数(df,*args,**kwa

如何添加一个装饰器,声明函数的传入dataframe参数具有datetime索引


我已经看过engarde和validada的包装,但还没有找到任何东西。我可以在函数内部执行此检查,但更喜欢装饰器。

这里有一个,有点像

[84]中的
:def具有_datetimeindex(func):
…:@wrapps(func)
…:def包装(df、*args、**kwargs):
…:断言isinstance(df.index,pd.DatetimeIndex)
…:返回函数(df,*args,**kwargs)
…:返回包装器
在[85]中:@has_datetimeindex
…:定义f(df):
…:返回df+1
[86]中的df=pd.DataFrame({'a':[1,2,3]})
In[87]:f(df)
---------------------------------------------------------------------------
AssertionError回溯(上次最近的调用)
在()
---->1楼(东风)
包装内(df,*args,**kwargs)
2@wrapps(func)
3个def包装(df、*args、**kwargs):
---->4断言isinstance(df.index,pd.DatetimeIndex)
5返回函数(df、*args、**kwargs)
6返回包装器
断言者错误:
在[88]中:df=pd.DataFrame({'a':[1,2,3]},index=pd.date\u range('2014-1-1',periods=3))
In[89]:f(df)
出[89]:
A.
2014-01-01  2
2014-01-02  3
2014-01-03  4

正如@PadraicCunningham所写,使用以下方法创建一个应用程序并不难:


为什么不创造你自己的呢?我的一半是我;)我不相信你。不可能我写得比你快。:-)哈哈,如果你看到我打字,你不会觉得很难相信:)那就更让人印象深刻了,即使是真的。
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
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)