修复 Python 错误 AttributeError: 'numpy.ndarray' Object Has No Attribute 'Append'
与列表或数组一样,NumPy 没有数组的 append()
方法; 相反,我们需要使用 NumPy 的 append()
方法。 我们可以使用 append()
方法添加多个 NumPy 数组。
Python 中 AttributeError: 'numpy.ndarray' object has no attribute 'append'
ndarray 是一个 n 维 NumPy 数组,可用于多种用途,例如当我们的模型具有多种数据类型时。 这是一个使用它的简单示例:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Type: {type(arr)}")
print(f"Dimension: {arr.ndim}")
print(f"Shape: {arr.shape}")
print(f"Element data type: {arr.dtype}")
输出:
Type: <class 'numpy.ndarray'>
Dimension: 2
Shape: (2, 3)
Element data type: int32
现在,让我们尝试在上面的 ndarray 对象中附加一个数组。 我们会得到以下错误:
>>> arr.append([1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'numpy.ndarray' object has no attribute 'append'
因此,很明显 ndarray 类型对象不包含任何称为 append()
的方法。
修复Python AttributeError: 'numpy.ndarray' object has no attribute 'append' 错误
要在 ndarray 对象中附加一个新数组,我们需要确保新数组与 ndarray 中的前一个数组具有相同的维度。
下面是我们将如何附加 ndarray:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.append(arr, [[7, 8, 9]], axis=0)
print(arr)
输出:
[[1 2 3]
[4 5 6]
[7 8 9]]
在这里,如果你注意到,我们将轴设为 0。现在,如果我们不提及轴,则会发生以下情况:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.append(arr, [[7, 8, 9]])
print(arr)
输出:
[1 2 3 4 5 6 7 8 9]
它只是解开所有元素,然后将其变成一个数组!
现在,让我们观察一下如果我们给出一个维度不同的数组会发生什么:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr = np.append(arr, [[7, 8]],axis=0)
输出:
这里我们得到了维度不匹配的 ValueError
。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串