python-3.x - 熊猫时间戳:这是什么类型的?
问题描述
我有一个带有解析时间戳的熊猫数据框。这是什么类型的?我尝试使用以下规则对其进行匹配:
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 匹配?
解决方案
Pandasdatetime64[ns]
是一种'<M8[ns]'
numpy 类型,因此您只需比较dtype
s:
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, ...)
不起作用,因为您将(当然)的类型dtype
numpy.dype
与其他数据 dtypes 进行比较,这对于任何数据类型自然都会失败。
推荐阅读
- office-ui-fabric - 覆盖 FluentUI 的 Picker 组件行为的最佳方法是什么?
- spring - 接口扩展多个接口
- sqlite - 我可以使用连接条件在 SQLite 中将数据从一个表复制到另一个表吗?
- java - Java 错误:-“找不到适合排序的方法(学生 [],j)”
- python - 如何使用日期、熊猫和 python 将数据集拆分为训练数据和测试数据?
- javascript - Ionic Cordova Run Browser 赋予设备权限
- docker - 启动容器进程导致“exec:\”/bin/sh\“:stat /bin/sh:没有这样的文件或目录”:
- powershell - 将用户数据从 Outlook 全局地址列表导出到文本或 excel 或 csv 文件
- java - javax.xml.stream.XMLStreamException:休眠配置文件中的 ParseError
- python - 如何计算数据框列中由分隔符分隔的子字符串并将值推送到新列中?