首页 > 解决方案 > 熊猫时间戳:这是什么类型的?

问题描述

我有一个带有解析时间戳的熊猫数据框。这是什么类型的?我尝试使用以下规则对其进行匹配:

dtype_dbg = df[col].dtype # debugger shows it as 'datetime64[ns]'
if isinstance(df[col].dtype,np.datetime64) # no luck
if isinstance(df[col].dtype,pd.Timestamp)  # ditto
if isinstance(df[col].dtype,[all other timestamps I could think of]) # nothing

如何与 pandas 数据框中的时间戳 dtype 匹配?

标签: python-3.xpandasdataframe

解决方案


Pandasdatetime64[ns]是一种'<M8[ns]'numpy 类型,因此您只需比较dtypes:

df = pd.DataFrame( {'col': ['2019-01-01', '2019-01-02']})
df.col = pd.to_datetime(df.col)
df.info()
#<class 'pandas.core.frame.DataFrame'>
#RangeIndex: 2 entries, 0 to 1
#Data columns (total 1 columns):
#col    2 non-null datetime64[ns]
#dtypes: datetime64[ns](1)
#memory usage: 144.0 bytes

df[col].dtype == np.dtype('<M8[ns]')
#True

您还可以(或者应该更好)使用 pandas 内置api.types.is_...函数

pd.api.types.is_datetime64_ns_dtype(df[col])
#True

您的比较isinstance(df[col].dtype, ...)不起作用,因为您将(当然)的类型dtypenumpy.dype与其他数据 dtypes 进行比较,这对于任何数据类型自然都会失败。


推荐阅读