为什么 `to_numpy()` 被识别为属性而不是数据框的方法?

Why is `to_numpy()` recognized as an attribute rather than a method of dataframe?

import pandas as pd
import numpy as np

class CLF:
    Weights = 0
    
    def fit(DF_input, DF_output, eta=0.1, drop=1000):
        X, y = DF_input.to_numpy(copy=True), DF_output.to_numpy(copy=True)
        N,d = X.shape
        m = len(np.unique(y))   
        self.Weights = np.random.normal(0,1, size=(d,m))


INPUT = pd.read_csv(path_input)
OUTPUT = pd.read_csv(path_output)
clf = CLF()
clf.fit(INPUT, OUTPUT)

我为我写的class定义了一个方法.fit()。第一步是将两个数据帧转换为 numpy 数组。但是,当我尝试使用该方法时出现以下错误,尽管 INPUT.to_numpy(copy=True)OUTPUT.to_numpy(copy=True) 都可以正常工作。有人可以帮我吗?为什么 to_numpy 被识别为 属性 而不是 数据帧方法

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-22-a3d455104534> in <module>
      1 clf = CLF()
----> 2 clf.fit(INPUT, OUTPUT)

<ipython-input-16-57babd738b2d> in fit(DF_input, DF_output, eta, drop)
      4 
      5     def fit(DF_input, DF_output, eta=0.1,drop=1000):
----> 6         X, y = DF_input.to_numpy(copy=True), DF_output.to_numpy(copy=True)
      7         N,d = X.shape
      8         m = len(np.unique(y))   # number of classes

AttributeError: 'CLF' object has no attribute 'to_numpy'

您的问题是对象方法的第一个输入通常保留给 self。正确的语法应该是:

class CLF:
    Weights = 0
    
    # notice the `self`
    def fit(self, DF_input, DF_output, eta=0.1, drop=1000):
        X, y = DF_input.to_numpy(copy=True), DF_output.to_numpy(copy=True)
        N,d = X.shape
        m = len(np.unique(y))   
        self.Weights = np.random.normal(0,1, size=(d,m))


INPUT = pd.read_csv(path_input)
OUTPUT = pd.read_csv(path_output)
clf = CLF()
clf.fit(INPUT, OUTPUT)

实例方法是一种属性;这是一条更一般的错误消息,它键入 .(点)运算符,而不是解析到左括号以区分您的用法。

问题是您定义了实例方法 fit,但将您的实例命名为 DF_input。我认为您只是忘记了通常的 self 隐式实例参数的命名方式。