gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:21:59 25 4
gpt4 key购买 nike

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

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

这可以用来修改 numpy 数组的获取/设置行为吗?

最佳答案

您可以实现 __getitem____setitem__ 来处理您的特定情况(使用日期时间对象)并分派(dispatch)给 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]]

关于python - 在 Numpy 数组子类中更改 `__getitem__` 和 `__setitem__` 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com