Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何测试对象是否是日期时间索引?_Python_Datetime_Indexing_Pandas - Fatal编程技术网

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

Python 如何测试对象是否是日期时间索引?,python,datetime,indexing,pandas,Python,Datetime,Indexing,Pandas,如果我在我知道有日期时间索引的数据帧上使用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
,我会得到:

In [17]: type(df.index)
Out[17]: pandas.tseries.index.DatetimeIndex
但当我测试它时,我得到:

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

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

您将熊猫作为什么导入

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

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强调不应该使用字符串来比较等价性时,我忽略了提及

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

In [103]: type("asd") == "str"
Out[103]: False
与对象而不是字符串进行比较。

您可以使用DatetimeIndex类:

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
[11]中的
:日期=pd.日期范围('20130101',期间=6)
在[12]中:日期
出[12]:
[2013-01-01 00:00:00, ..., 2013-01-06 00:00:00]
长度:6,频率:D,时区:无
在[13]中:isinstance(日期,pd.DatetimeIndex)
Out[13]:对

解决方案是不要与字符串进行比较,但要与对象进行比较,谢谢。我失败了2分。我知道字符串位,但考虑到我试图针对pandas.tseries.index.DatetimeIndex进行测试,我不知道还可以尝试什么。针对我导入的pd.tseries.index.DatetimeIndex进行测试,成功了。这并没有检查日期是否是DatetimeIndex,只是x[0]是一个时间戳。。。它可能是一个列表或系列等,第0项有时间戳。我想我已经走了很长一段路,因为我问了这个问题。。。(:谢谢你的回答!欢迎来到StackOverflow!
In : type(df.index)  
Out: pandas.core.indexes.datetimes.DatetimeIndex


In : type(df.index) == pd.core.indexes.datetimes.DatetimeIndex  
Out: True