Numpy报”AttributeError:’numpy.ndarray’object has no attribute’append’ “的原因以及解决办法

  • Post category:Python

问题描述:

在使用numpy的ndarray时,执行array.append()时报错,提示“AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’”。

问题原因:

ndarray是一种高性能多维数组的数据结构,它在创建时就已经固定了大小,因此不支持使用append()等动态修改数组大小的方法。

解决办法:

1.使用numpy中提供的其他方法来实现对数组的修改,比如:

  • 使用np.concatenate()方法拼接两个数组
  • 使用np.insert()方法在指定位置插入元素
  • 使用np.delete()方法删除指定位置的元素

2.使用Python中提供的列表list代替ndarray

如果需要动态修改数组大小,可以使用Python中提供的列表来实现:

import numpy as np
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.append(list2)
# 输出结果:[1, 2, 3, [4, 5, 6]]

3.在创建ndarray时,可以使用numpy中提供的resize()或者reshape()方法来实现对数组大小的修改

  • np.resize(a, new_shape)方法可将数组a的大小调整为new_shape,不够的地方用0补齐,多余的删除。
  • np.reshape(a, new_shape)方法可将数组a的形状调整为new_shape,但不能修改数组的大小。

参考代码:

import numpy as np

# 1.np.concatenate()方法拼接两个数组
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.concatenate((arr1, arr2))
# 输出结果:[1, 2, 3, 4, 5, 6]

# 2.np.insert()方法在指定位置插入元素
arr1 = np.array([1, 2, 3])
arr2 = np.insert(arr1, 1, 4)
# 输出结果:[1, 4, 2, 3]

# 3.np.delete()方法删除指定位置的元素
arr1 = np.array([1, 2, 3])
arr2 = np.delete(arr1, 1)
# 输出结果:[1, 3]

# 4.使用Python中的列表代替ndarray
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.append(list2)
# 输出结果:[1, 2, 3, [4, 5, 6]]

# 5.np.resize()方法调整ndarray的大小
arr1 = np.array([1, 2, 3])
arr2 = np.resize(arr1, (2, 2))
# 输出结果:[[1, 2],
#         [3, 1]]

# 6.np.reshape()方法调整ndarray的形状
arr1 = np.array([1, 2, 3, 4])
arr2 = np.reshape(arr1, (2, 2))
# 输出结果:[[1, 2],
#         [3, 4]]

以上就是解决”AttributeError: ‘numpy.ndarray’ object has no attribute ‘append'”错误的完整攻略。