numpy.append#
- numpy.append(arr, values, axis=None)[原始碼]#
將值附加到陣列的末尾。
- 參數:
- arrarray_like
值會附加到此陣列的副本。
- valuesarray_like
這些值會附加到 arr 的副本。它必須具有正確的形狀(與 arr 相同的形狀,排除 axis)。如果未指定 axis,則 values 可以是任何形狀,並在使用前展平。
- axisint, optional
沿著此軸 values 會被附加。如果未給定 axis,則 arr 和 values 都會在用前展平。
- 返回:
- appendndarray
傳回一個複製的 arr,其中 values 已附加到 axis。 請注意,
append
並非就地操作:會分配並填入一個新陣列。 如果 axis 為 None,則 out 會是一個扁平化的陣列。
範例
>>> 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
,因此當附加 dtypeint64
時,輸出 dtype 也會是float64