StiffnessMatrix
的实例基本上是一个2D数组和一个名为dofs
的额外1D数组,具有相同长度作为属性。
class StiffnessMatrix(np.ndarray):
def __new__(cls, input_array, dofs=None):
# Input array is an already formed ndarray instance
# We first cast to be our class type
obj = np.asarray(input_array).view(cls)
obj.dofs= dofs
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.dofs = getattr(obj, 'dofs', None)
我需要做的只是将StiffnessMatrix
和dofs
切片如下:
A = np.eye(4, 4) # random 4x4 array
dofs = np.arange(4) # random 1x4 array
#Create an instance
OldMatrix = StiffnessMatrix(A, dofs=dofs)
# MY CURRENT WAY
#New view on the instance
NewMatrix = OldMatrix[2:, 2:]
NewMatrix.dofs = OldMatrix.dofs[2:]
NewMatrix.dofs
>> [2, 3]
有没有一种方法可以在类中进行最后一个操作,如下所示?
# MY DESIRED WAY
NewMatrix = OldMatrix[2:, 2:]
NewMatrix.dofs
>> [2, 3]
我知道这听起来很无聊,而且我知道有一种使用pandas
的方法,我很好奇。