我想继承numpy ndarray。但是,我不能更改数组。为什么self = ...
不更改数组?谢谢。
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?
最佳答案
也许使它成为一个函数,而不是一个方法:
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')])
或者,如果您希望将其作为一种方法,
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
的新实例。关于python - 子类化numpy ndarray问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5149269/