在 Numpy 数组子类中更改 `__getitem__` 和 `__setitem__` 的行为

Changing behavior of `__getitem__` and `__setitem__` in Numpy array subclass

Numpy arrays can be efficiently subclassed,但我想修改 __getitem____setitem__ 的行为,以便它们可以接受日期时间范围,同时保留最大数量的内置机器,例如操作、cumsum 等。这可以用 __array_ufunc__ 来完成吗?

他们的 example, the numpy.ufunc.at 方法似乎被覆盖了。

这可以用来修改 numpy 数组的 get/set 行为吗?

您可以实施 __getitem____setitem__ 来处理您的特定情况(使用 datetime 对象)并在其他情况下分派到 super().__{get|set}item__。这样 ndarray 的剩余功能将保留。例如:

from datetime import date
import numpy as np

class A(np.ndarray):
    def __array_finalize__(self, obj):
        if obj is not None:
            obj.start_date = date.today()

    def __getitem__(self, item):
        if isinstance(item, slice) and isinstance(item.start, date) and isinstance(item.stop, date):
            return super().__getitem__(slice((item.start - self.start_date).days,
                                             (item.stop - self.start_date).days,
                                             item.step))
        return super().__getitem__(item)

a = A((10,), buffer=np.arange(10), dtype=int)
print(a[1:8])
print(a[date(2019, 1, 22):date(2019, 1, 29):2])
print(np.cumsum(a))
print(np.add.outer(a, a))

输出:

[1 2 3 4 5 6 7]
[1 3 5 7]
[ 0  1  3  6 10 15 21 28 36 45]
[[ 0  1  2  3  4  5  6  7  8  9]
 [ 1  2  3  4  5  6  7  8  9 10]
 [ 2  3  4  5  6  7  8  9 10 11]
 [ 3  4  5  6  7  8  9 10 11 12]
 [ 4  5  6  7  8  9 10 11 12 13]
 [ 5  6  7  8  9 10 11 12 13 14]
 [ 6  7  8  9 10 11 12 13 14 15]
 [ 7  8  9 10 11 12 13 14 15 16]
 [ 8  9 10 11 12 13 14 15 16 17]
 [ 9 10 11 12 13 14 15 16 17 18]]