【问题标题】:Asserting that pandas dataframe has a datetime index through decorator通过装饰器断言 pandas 数据框具有日期时间索引
【发布时间】:2016-02-03 20:23:25
【问题描述】:

如何添加装饰器,说明传入的 pandas 数据帧参数到函数具有日期时间索引?

我查看了 engarde 和 validada 包,但还没有找到任何东西。我可以在函数内部做这个检查,但更喜欢装饰器。

【问题讨论】:

  • 为什么不自己创建呢?

标签: python pandas decorator datetimeindex


【解决方案1】:

正如@PadraicCunningham 所写,使用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)

【讨论】:

  • 还有我的一半;)
  • 我不相信你。没办法,我写的东西比你快。 :-)
  • 大声笑,如果你看到我打字,你不会觉得很难相信 :)
  • 这让它更令人印象深刻,即使是真的。
【解决方案2】:

这是一个,有点仿照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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2021-03-27
    • 2020-06-04
    • 2021-08-14
    • 2018-07-31
    • 1970-01-01
    • 2012-12-01
    • 2018-11-23
    相关资源
    最近更新 更多