在使用Python时,你可能遇到的一个错误是:
TypeError: 'numpy.float64' object is not callable
这个错误可能发生在两种不同的情况下:
- 情形1: 没有使用*号的乘法
- 情形2:没有使用NumPy Min函数
下面的例子说明了如何在每种情况下解决这个错误。
情形1:没有使用*号的乘法
假设我们试图将两个NumPy数组相乘而不使用乘号(*),如下所示:
import numpy as np
#define arrays
x = np.array([1, 2, 3, 4, 5])
y = np.array([12, 14, 14, 19, 22])
#attempt to multiply two arrays together
combo = (x)(y)
#view result
print(combo)
TypeError: 'numpy.float64' object is not callable
我们会收到一个TypeError,因为我们在尝试将两个数组相乘时没有使用乘号(*)。
避免这个错误的方法是确保我们使用了乘号:
import numpy as np
#define arrays
x = np.array([1, 2, 3, 4, 5])
y = np.array([12, 14, 14, 19, 22])
#multiply two arrays together
combo = (x)*(y)
#view result
print(combo)
[ 12 28 42 76 110]
注意,这次我们没有收到错误。
情景2:没有使用NumPy Min函数
假设我们使用下面的代码试图找到一个NumPy数组的最小值:
import numpy as np
#define array of data
data = np.array([3.3, 4.1, 4, 5.6, 8.1, 9.9, 9.7, 10.2])
#attempt to find minimum value of array
min_val = min(data)
#view minimum value
print(min_val)
TypeError: 'numpy.float64' object is not callable
我们收到一个TypeError,因为我们使用了**min()**函数。
相反,我们需要使用np.min(),如下所示:
import numpy as np
#define array of data
data = np.array([3.3, 4.1, 4, 5.6, 8.1, 9.9, 9.7, 10.2])
#attempt to find minimum value of array
min_val = np.min(data)
#view minimum value
print(min_val)
3.3
注意,这次我们没有收到错误。
其他资源
下面的教程解释了如何修复Python中的其他常见错误:
如何修复:列重叠但没有指定后缀
如何修复:'numpy.ndarray'对象没有属性'append'
如何修复:如果使用所有标量值,必须传递一个索引
如何修复。ValueError:无法将浮点数NaN转换为整数