You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为自定义 dtype 定义 Pandas 类型转换规则?

问题:自定义SpecialTime类型无法在Pandas中转为datetime类型

我实现了一个特殊的date dtype,出于多种原因无法直接使用原生date类型(原生类型存在一系列问题)。希望在Pandas中该类型能被完全当作内置datetime类型处理,但目前始终无法解决TypeError: <class '__main__.SpecialTime'> is not convertible to datetime错误,相关代码如下:

from datetime import date, datetime

import numpy as np
import pandas as pd
from pandas.api.extensions import ExtensionDtype


class SpecialTime(ExtensionDtype):
    name = "SpecialTime"
    na_value = None

    @classmethod
    def construct_array_type(cls):
        return pd.arrays.DatetimeArray

    def __init__(self, year, month, day):
        self._date = date(year, month, day)

    def __str__(self):
        return str(self._date)

    def to_datetime(self):
        return datetime.combine(self._date, datetime.min.time())

    # 尝试添加该方法避免TypeError: <class '__main__.SpecialTime'> is not convertible to datetime
    def __array__(self, dtype=None):
        return np.array([self.to_datetime()], dtype="datetime64[ns]")


pd.api.extensions.register_extension_dtype(SpecialTime)

df = pd.DataFrame(
    {
        "date_column": [
            SpecialTime(2022, 1, 1),
            SpecialTime(2023, 1, 2),
            SpecialTime(2024, 1, 3),
        ]
    }
)
print(df.dtypes)
print(df.convert_dtypes().dtypes)
print(df.astype("datetime64[ns]").dtypes)

内容的提问来源于stack exchange,提问作者komodovaran_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:46:07