numpy.append()中axis参数的使用详解

沈知远
沈知远
发布时间:2026-10-13 | 2人浏览过
原创

本文详细解析numpy.append()函数中axis参数的作用。当axis未指定时,数组展平为一维;axis为0时沿行追加(需列数一致),axis为1时沿列追加(需行数一致)。通过代码示例展示不同axis值下的数组组合结果及常见错误处理。

具体用法如下所示:

def append(arr, values, axis=None):
 """
 Append values to the end of an array.
 Parameters
 ----------
 arr : array_like
  Values are appended to a copy of this array.
 values : array_like
  These values are appended to a copy of `arr`. It must be of the
  correct shape (the same shape as `arr`, excluding `axis`). If
  `axis` is not specified, `values` can be any shape and will be
  flattened before use.
 axis : int, optional
  The axis along which `values` are appended. If `axis` is not
  given, both `arr` and `values` are flattened before use.
 Returns
 -------
 append : ndarray
  A copy of `arr` with `values` appended to `axis`. Note that
  `append` does not occur in-place: a new array is allocated and
  filled. If `axis` is None, `out` is a flattened array.

numpy.append(arr, values, axis=None):

简单来说,该函数会将arr和values组合生成一个新的数组作为返回值。其中,axis是一个可选参数。

当axis参数未定义(即None)时,数组会进行横向拼接,最终返回的始终是一个一维数组。

 Examples
 --------
 >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
 array([1, 2, 3, 4, 5, 6, 7, 8, 9])

当axis参数有具体定义时,主要涉及0和1两种情况。(注意:在加载数据时,必须确保数组的形状匹配,即行数或列数需相同,否则会报错:all the input array dimensions except for the concatenation axis must match exactly)。

当axis设置为0时,数组会在下方进行拼接(此时要求列数相同):

import numpy as np
aa= np.zeros((1,8))
bb=np.ones((3,8))
c = np.append(aa,bb,axis = 0)
print(c)
[[ 0. 0. 0. 0. 0. 0. 0. 0.]
 [ 1. 1. 1. 1. 1. 1. 1. 1.]
 [ 1. 1. 1. 1. 1. 1. 1. 1.]
 [ 1. 1. 1. 1. 1. 1. 1. 1.]]

当axis设置为1时,数组会在右侧进行拼接(此时要求行数相同):

import numpy as np
aa= np.zeros((3,8))
bb=np.ones((3,1))
c = np.append(aa,bb,axis = 1)
print(c)
[[ 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [ 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [ 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

以上就是对numpy.append()函数中axis参数用法的详细解析,希望以上内容能为大家提供参考,也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表