“ TypeError:'numpy.ndarray'对象不可调用”是什么意思?

时间:2019-09-20 22:24:24

标签: python arrays pandas numpy

我正在开发一个简单的房价预测机器学习模型。运行时出现此错误,不知道为什么。我已经读到,这意味着我试图将numpy数组作为函数调用,但是由于我没有看到代码中发生的情况,所以我并不真正理解这意味着什么。在这里:

Path = "housedata"
Name = "data.csv"
df = pd.read_csv(os.path.join(Path, Name))
df2 = df.apply(preprocessing.LabelEncoder().fit_transform)
df2 = df2.drop(columns=["date", "yr_renovated", "street", "city", "statezip", "country"])

predictors = df2.drop(columns=["price"])
target = df2["price"].values()
x_train, x_test, y_train, y_test = train_test_split(predictors, target, 
                                                    test_size=0.2, random_state=1)

model = LinearRegression()
model.fit(x_train, y_train)
print (regr.score(x_test, y_test))

完整错误是:

Traceback (most recent call last):
  File "housemodel.py", line 19, in <module>
    target = df2["price"].values()
TypeError: 'numpy.ndarray' object is not callable

有人解决吗?谢谢。

2 个答案:

答案 0 :(得分:1)

很可能df["price"].values返回一个numpy.ndarray,然后()尝试调用一个数组(这不会发生;只能调用方法/函数)。放下()

target = df2["price"].values

答案 1 :(得分:0)

每当您收到此类错误... object is not callable时。这意味着您正在调用属性而不是方法

为了更好地解释它。考虑这个例子。

class Person(object):
  """ Person class """

  def __init__(self, name, age):
    """ Initialize Person"""
    self.name = name
    self.age = age

  def getname(self):
    return self.name

  def getage(self):
    return self.age

  profession = 'Oncologist'


doctor1 = Person('Dr. Prabhaharan', 45)
# Gives correct output
print(doctor1.profession)

# Gives correct output
print(doctor1.getage())

# Gives a similar output which you got.
print(doctor1.profession())