本文介绍了子类化numpy ndarray问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想继承numpy ndarray.但是,我不能更改数组.为什么self = ...
不更改数组?谢谢.
I would like to subclass numpy ndarray. However, I cannot change the array. Why self = ...
does not change the array? Thanks.
import numpy as np
class Data(np.ndarray):
def __new__(cls, inputarr):
obj = np.asarray(inputarr).view(cls)
return obj
def remove_some(self, t):
test_cols, test_vals = zip(*t)
test_cols = self[list(test_cols)]
test_vals = np.array(test_vals, test_cols.dtype)
self = self[test_cols != test_vals] # Is this part correct?
print len(self) # correct result
z = np.array([(1,2,3), (4,5,6), (7,8,9)],
dtype=[('a', int), ('b', int), ('c', int)])
d = Data(z)
d.remove_some([('a',4)])
print len(d) # output the same size as original. Why?
推荐答案
也许使它成为函数而不是方法:
Perhaps make this a function, rather than a method:
import numpy as np
def remove_row(arr,col,val):
return arr[arr[col]!=val]
z = np.array([(1,2,3), (4,5,6), (7,8,9)],
dtype=[('a', int), ('b', int), ('c', int)])
z=remove_row(z,'a',4)
print(repr(z))
# array([(1, 2, 3), (7, 8, 9)],
# dtype=[('a', '<i4'), ('b', '<i4'), ('c', '<i4')])
或者,如果您希望将其用作方法,
Or, if you want it as a method,
import numpy as np
class Data(np.ndarray):
def __new__(cls, inputarr):
obj = np.asarray(inputarr).view(cls)
return obj
def remove_some(self, col, val):
return self[self[col] != val]
z = np.array([(1,2,3), (4,5,6), (7,8,9)],
dtype=[('a', int), ('b', int), ('c', int)])
d = Data(z)
d = d.remove_some('a', 4)
print(d)
这里的主要区别是remove_some
不会尝试修改self
,它只会返回Data
的新实例.
The key difference here is that remove_some
does not try to modify self
, it merely returns a new instance of Data
.
这篇关于子类化numpy ndarray问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!