[英]how to fix this error 'numpy.ndarray' object has no attribute 'append' in the code below
Returns this error: 'numpy.ndarray' object has no attribute 'append'返回此错误:'numpy.ndarray' 对象没有属性 'append'
class1 = np.array([]) #creates 2 empty arrays
class2 = np.array([])
#yhat_tr is a vector(1 column, 100 rows) = numpy.ndarray
for i in yhat_tr:
if i < 0:
class1.append([i]) #insert the iten in the array class1 or class2
else:
class2.append([i])
I want to insert new array itens inside the class1 or class2 arrays as soon the itens are evaluated inside the loop.我想在循环内评估 itens 后立即在 class1 或 class2 数组中插入新的数组 itens。 After that i will try to print the results in a scatter graphic with 2 colors where i can identify visually the class1 and class2 elements.之后,我将尝试在具有 2 种颜色的散点图中打印结果,我可以在其中直观地识别 class1 和 class2 元素。
You can add a NumPy array element by using the append() method of the NumPy module.您可以使用 NumPy 模块的 append() 方法添加 NumPy 数组元素。
The syntax of append is as follows: append 的语法如下:
numpy.append(array, value, axis)
The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above.这些值将附加在数组的末尾,并且将返回一个新的 ndarray,其中包含新旧值,如上所示。
The axis is an optional integer along which define how the array is going to be displayed.轴是一个可选的整数,沿着它定义数组将如何显示。 If the axis is not specified, the array structure will be flattened如果没有指定轴,数组结构将被展平
A quick look at the documentation shows that np.ndarray
objects do not have a function append
, it is a function of np
itself:快速查看文档表明np.ndarray
对象没有函数append
,它是np
本身的函数:
class1 = np.append(class1, [i])
As @Alex mentioned, numpy arrays dont have append method.正如@Alex 提到的,numpy 数组没有 append 方法。 You can use his suggestion to use numpy append method or You might want to define class variables as lists and use append and convert them to array after the loop as the code below does.您可以使用他的建议使用 numpy append 方法,或者您可能希望将类变量定义为列表并使用 append 并在循环后将它们转换为数组,如下面的代码所示。
class1 = []
class2 = []
#yhat_tr is a vector(1 column, 100 rows) = numpy.ndarray
for i in yhat_tr:
if i < 0:
class1.append([i]) #insert the iten in the array class1 or class2
else:
class2.append([i])
class1 = np.array(class1)
class2 = np.array(class2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.