问题描述
我想创建一个numpy.recarray的子类,当将数据添加到当前长度之外的行时,该子类会自动调整大小.
I'd like to create a subclass of numpy.recarray that automatically resizes when data is added to a row outside of its current length.
下面的代码满足了我的大部分需求.
The code below does most of what I want.
class autorecarray(numpy.recarray):
def __init__(self,*args,**kwargs):
self._increment = 1
numpy.recarray.__init__(self,args,kwargs)
def __setitem__(self,ind,y):
try:
numpy.recarray.__setitem__(self,ind,y)
except IndexError:
self.resize((self.__len__()+self._increment,),refcheck=False)
self.__setitem__(ind,y)
在此用例中效果很好:
a = utils.autorecarray((1,),formats=['i4','i4'])
a[1] = (1,2) # len(a) will now be 2
但是,这种用法将在numpy.core.records.recarray __getitem__
方法上引发IndexError:
However, this usage will raise an IndexError on numpy.core.records.recarray __getitem__
method:
a[2]['f1'] = 3
我最初的尝试是也重写子类中的__getitem__
方法,但是此代码不起作用.
My initial attempt was to also override the __getitem__
method in my subclass, but this code does not work.
def __getitem__(self,ind):
try:
numpy.recarray.__getitem__(self,ind)
except IndexError:
self.resize((self.__len__() + self._increment,),refcheck=False)
self.__getitem__(ind)
它会自动扩展数组,但是现在数组中的每个项目都是None
,无法更改.
It does automatically expand the array, but now every item in the array is None
and cannot be changed.
有人可以告诉我我在做什么错吗?
Can anyone tell me what I'm doing wrong?
推荐答案
首先,您在numpy.recarray.__init__
调用中缺少星号:
First of all you're missing the asterisks in the numpy.recarray.__init__
call:
def __init__(self, *args, **kwargs):
self._increment = 1
numpy.recarray.__init__(self, *args, **kwargs)
第二,您在__getitem__
中缺少return
语句:
And second, you're missing return
statements in the __getitem__
:
def __getitem__(self,ind):
try:
return numpy.recarray.__getitem__(self,ind)
except IndexError:
self.resize((self.__len__() + self._increment,),refcheck=False)
return self.__getitem__(ind)
这篇关于自动调整NumPy Recarray的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!