我想趕緊寫點類,其中底層2D numpy.matrix
的每一列被分配到一個屬性 ,這樣我可以寫這樣的東西很容易:擴展numpy.matrix會產生__new__和__class__問題嗎?
points = Points(np.mat(np.ones((2,3))), names=["a","b","c"])
points.a = points.b + points.c
points["a"] = points["b"] + points["c"]
我想出了這樣的「猴子補丁」
class Points(np.matrixlib.defmatrix.matrix):
def __new__(cls, *args, names=[], **kwargs):
o = np.matrixlib.defmatrix.matrix.__new__(cls, *args, **kwargs)
o.__class__ = Points
return o
def __init__(self, *args, names=[], **kwargs):
# Set the attribute self.<pointName>
# to a reference of the corresponding column
for i,name in enumerate(names):
self.__setattr__(name, self[:,i])
我想知道是否有做暴力破解o.__class__ = Points
的更好的方法。 我需要這樣做,因爲Points.__init__
不會被調用,因爲type(o) != Points
。
全班同學正在這裏 https://gist.github.com/gabyx/9392992d11bf8550e44002ac7f1ecaaf
爲什麼不只是使用[pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html)或[NumPys結構化數組](https://docs.scipy .ORG/DOC/numpy的/用戶/ basics.rec.html)?這些列已經有了列和行訪問操作。 – MSeifert
記錄數組(np.rec.array)將爲您提供字段訪問的點符號。 – Eric
我也這麼認爲,但是結構化數組很難操縱,讓我們說通過矩陣很容易地轉換所有點... – Gabriel