0

我正在尝试在 python 中创建一个自定义日期时间类来支持时间序列模型。在查看了一些现有的 python 库后,我发现 pandas DatetimeIndex 类提供了我正在寻找的大部分功能,但我仍然想添加一些方法来满足我的需要。我尝试使用自定义初始化构造函数对 DatetimeIndex 类进行子类化,然后调用超级初始化构造函数,但我似乎无法让它工作。有人做过吗?了解如何实现这一点会很棒。

这是我能想到的最简单的例子。这是一个在名为 time 的模块中定义的类:

from pandas import DatetimeIndex

class DatetimeSub(DatetimeInex):

    def __init___(initTime):

        super().__init__(initTime)

当我使用以下代码在控制台中测试该类时:

import numpy as np

from time import DatetimeSub

testTime =  TimeEfo2(np.arange('1985-01-01 12:00','1985-02-01 12:00', dtype="datetime64[D]"))

我收到以下错误:

类型错误:对象。init () 只接受一个参数(要初始化的实例)

我不明白,因为您可以使用 datetime64 数组实例化 DatetimeIndex 。此代码工作正常:

from pandas import DatetimeIndex

import numpy as np

dT = DatetimeIndex(np.arange('1985-01-01 12:00','1985-02-01 12:00', dtype="datetime64[D]"))

谢谢khuynh!这样可行。如果我想创建自己的自定义构造函数,例如:

from pandas import DatetimeIndex
import numpy as np

class DatetimeSub(DatetimeIndex):
    def __init__(self, bgnTime, endTime, unit = 'D'):
        # I am now constructing my numpy datetime64 array here:
        initTime = np.arange(bgnTime, endTime, dtype="datetime64[{}]".format(unit))
        # How do I call the super class to populate with the numpy array? This does not work:
        super().__init__(initTime)

谢谢!

4

1 回答 1

0

构造函数的第一个参数始终是self。因此,如果您想initTime作为第二个参数传入,则需要将其添加到构造函数中,如下所示:

from pandas import DatetimeIndex
import numpy as np

class DatetimeSub(DatetimeIndex):
    def __init__(self, initTime):
        super().__init__()

dt = DatetimeIndex(np.arange('1985-01-01 12:00','1985-02-01 12:00', dtype="datetime64[D]"))

ds = DatetimeSub(np.arange('1985-01-01 12:00','1985-02-01 12:00', dtype="datetime64[D]"))

print(dt)

print(ds)

输出:

DatetimeIndex(['1985-01-01', '1985-01-02', '1985-01-03', '1985-01-04',
               '1985-01-05', '1985-01-06', '1985-01-07', '1985-01-08',
               '1985-01-09', '1985-01-10', '1985-01-11', '1985-01-12',
               '1985-01-13', '1985-01-14', '1985-01-15', '1985-01-16',
               '1985-01-17', '1985-01-18', '1985-01-19', '1985-01-20',
               '1985-01-21', '1985-01-22', '1985-01-23', '1985-01-24',
               '1985-01-25', '1985-01-26', '1985-01-27', '1985-01-28',
               '1985-01-29', '1985-01-30', '1985-01-31'],
              dtype='datetime64[ns]', freq=None)
DatetimeSub(['1985-01-01', '1985-01-02', '1985-01-03', '1985-01-04',
             '1985-01-05', '1985-01-06', '1985-01-07', '1985-01-08',
             '1985-01-09', '1985-01-10', '1985-01-11', '1985-01-12',
             '1985-01-13', '1985-01-14', '1985-01-15', '1985-01-16',
             '1985-01-17', '1985-01-18', '1985-01-19', '1985-01-20',
             '1985-01-21', '1985-01-22', '1985-01-23', '1985-01-24',
             '1985-01-25', '1985-01-26', '1985-01-27', '1985-01-28',
             '1985-01-29', '1985-01-30', '1985-01-31'],
            dtype='datetime64[ns]', freq=None)
于 2020-05-03T03:40:24.523 回答