2024-09-30 20:30:03 发布
网友
如何添加一个decorator,声明函数的传入pandas dataframe参数具有日期时间索引?在
我看过engarde和validada的包裹,但还没有找到任何东西。我可以在函数内部做这个检查,但是我更喜欢一个装饰器。在
{padningham很难使用@ccungham来创建:
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)
这里有一个,有点类似于^{}
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
{padningham很难使用@ccungham来创建:
这里有一个,有点类似于^{}
相关问题 更多 >
编程相关推荐