【问题标题】:How do I test if an object is a pandas datetime index?如何测试对象是否为 pandas 日期时间索引?
【发布时间】:2014-01-28 14:11:35
【问题描述】:

如果我在我知道有日期时间索引的DataFrame 上使用type,我会得到:

In [17]: type(df.index)
Out[17]: pandas.tseries.index.DatetimeIndex

但是当我测试它时,我得到:

In [18]: type(df.index) == 'pandas.tseries.index.DatetimeIndex'
Out[18]: False

我知道我假设 type 的类型是一个字符串,但我真的不知道还能尝试什么,并且搜索没有任何结果。

【问题讨论】:

    标签: python datetime indexing pandas


    【解决方案1】:
    In : type(df.index)  
    Out: pandas.core.indexes.datetimes.DatetimeIndex
    
    
    In : type(df.index) == pd.core.indexes.datetimes.DatetimeIndex  
    Out: True
    

    【讨论】:

    • 感谢您的回答!欢迎使用 StackOverflow!
    【解决方案2】:

    可以使用 DatetimeIndex 类的isinstance

    In [11]: dates = pd.date_range('20130101', periods=6)
    
    In [12]: dates
    Out[12]: 
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2013-01-01 00:00:00, ..., 2013-01-06 00:00:00]
    Length: 6, Freq: D, Timezone: None
    
    In [13]: isinstance(dates, pd.DatetimeIndex)
    Out[13]: True
    

    【讨论】:

    • 自问这个问题以来,我想我已经走了很长一段路... (-:
    【解决方案3】:

    您将 Pandas 导入为什么?

    如果您遵循文档中的指南并执行以下操作:

    import pandas as pd
    dates = pd.date_range('20130101', periods=6)
    
    type(dates[0]) 
    pandas.tslib.TimestampTimestamp('2013-01-01 00:00:00', tz=None)
    
    type(dates[0]) == pandas.tslib.Timestamp
    False  
    # this throws NameError since you didn't import as pandas
    
    type(dates[0]) == pd.tslib.Timestamp
    True  
    # this works because we imported Pandas as pd
    

    出于习惯,我没有提到 @M4rtini 强调您不应该使用字符串来比较等价性。

    【讨论】:

    • 解决办法是不比较字符串,而是对象
    • 谢谢。我有2分失败。我知道的字符串位,但考虑到我尝试针对 pandas.tseries.index.DatetimeIndex 进行测试,我不知道还能尝试什么。对 pd.tseries.index.DatetimeIndex 进行测试,这是我导入它的方式,成功了。
    • 这不会检查日期是否是 DatetimeIndex,只是检查 x[0] 是时间戳...它可以是列表或系列等,第 0 项是时间戳。
    【解决方案4】:
    In [102]: type("asd") == str
    Out[102]: True
    
    In [103]: type("asd") == "str"
    Out[103]: False
    

    比较对象,而不是字符串。

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 2019-06-22
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多