If I use type
on a DataFrame
which I know has a datetime index, I get:
如果我在一个DataFrame上使用类型,我知道它有一个datetime索引,我得到:
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.
我知道我假设类型是字符串,但我真的不知道还需要尝试什么,搜索没有结果。
3 个解决方案
#1
14
You can use isinstance of 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
#2
5
What did you import Pandas as?
你们进口的熊猫是什么?
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强调了不应该使用字符串来比较相等性。
#3
3
In [102]: type("asd") == str
Out[102]: True
In [103]: type("asd") == "str"
Out[103]: False
Compare against the object, not a string.
比较对象,而不是字符串。
#1
14
You can use isinstance of 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
#2
5
What did you import Pandas as?
你们进口的熊猫是什么?
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强调了不应该使用字符串来比较相等性。
#3
3
In [102]: type("asd") == str
Out[102]: True
In [103]: type("asd") == "str"
Out[103]: False
Compare against the object, not a string.
比较对象,而不是字符串。