Python 如何测试对象是否是熊猫日期时间索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21030174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:51:02  来源:igfitidea点击:

How do I test if an object is a pandas datetime index?

pythondatetimeindexingpandas

提问by piRSquared

If I use typeon a DataFramewhich I know has a datetime index, I get:

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

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

but when I test it, I get:

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

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

I know I assumed the type of type is a string, but I really don't know what else to try, and searching has resulted in nothing.

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

采纳答案by Andy Hayden

You can use isinstanceof the DatetimeIndex class:

您可以使用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

回答by Matthew

What did you import Pandas as?

你导入 Pandas 作为什么?

If you are following the guide in the documentation and did something like:

如果您按照文档中的指南进行操作并执行以下操作:

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

Out of habit I neglected to mention as @M4rtini highlighted that you should not be using a string to compare equivalency.

出于习惯,我忽略了提及,因为@M4rtini 强调您不应该使用字符串来比较等效性。

回答by M4rtini

In [102]: type("asd") == str
Out[102]: True

In [103]: type("asd") == "str"
Out[103]: False

Compare against the object, not a string.

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