numpy.append#

numpy.append(arr, values, axis=None)[源代码]#

将值追加到数组的末尾.

参数:
arrarray_like

这些值将追加到此数组的副本.

valuesarray_like

这些值将追加到 arr 的副本. 它必须具有正确的形状(与 arr 相同的形状,不包括 axis ). 如果未指定 axis ,则 values 可以是任何形状,并且在使用前将被展平.

axis整数,可选

values 被附加的轴.如果未指定 axis ,则在使用前将 arrvalues 都展平.

返回:
appendndarray

一个将 values 附加到 axisarr 的副本.请注意, append 不会就地发生:会分配并填充一个新数组.如果 axis 为 None,则 out 是一个扁平化数组.

参见

insert

将元素插入到数组中.

delete

从数组中删除元素.

示例

>>> import numpy as np
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, ..., 7, 8, 9])

当指定 axis 时, values 必须具有正确的形状.

>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
    ...
ValueError: all the input arrays must have same number of dimensions, but
the array at index 0 has 2 dimension(s) and the array at index 1 has 1
dimension(s)
>>> a = np.array([1, 2], dtype=int)
>>> c = np.append(a, [])
>>> c
array([1., 2.])
>>> c.dtype
float64

空 ndarray 的默认 dtype 是 float64 ,因此当附加 dtype int64 时,输出的 dtype 为 float64 .