Python中Numpy.append的用法解析

之前只見過列表list的append方法,昨天寫代碼的時候,看到了numpy庫的append方法,記錄一下。

簡單的說,該方法功能就是將一個數組附加到另一個數組的尾部

目錄

官方幫助文檔

參數

返回值

示例

axis無定義

axis=0的情況

axis=1的情況

axis=0和axis=1的圖示


先看一個官方的幫助文檔,嫌麻煩的可以直接看示例。看完示例再反過頭看文檔,其實理解的更好。

官方幫助文檔

append(arr, values, axis=None)

Append values to the end of an array.  將值附加到數組的末尾。

參數

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.

這些值附加到"arr"的副本上。 它必須是正確的形狀(與"arr"形狀相同,不包括"軸")。 如果未指定"axis",則"values"可以是任何形狀,並在使用前展平。

“與"arr"形狀相同,不包括"軸"”,這句話的意思是說,一個數組兩維,如果axis=0,則axis=1這一維形狀要相同。如果設置了axis=1,則axis=0這一維要相同,具體可以看後面的例子。

axis : int, optional

The axis along which "values" are appended.  If `axis` is not given, both `arr` and `values` are flattened before use.

附加“值”的軸。 如果沒有給出`axis`,'arr`和`values`在使用前都會展平。

返回值

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.

 帶有"values"的"arr"的副本附加到"axis"。注意,"append"並不是就地發生的:一個新的數組被分配和填充。如果"axis"爲空,則"out"是一個扁平數組。

示例

axis無定義

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

返回由arr和values組成的新數組。axis是一個可選的值,當axis無定義時,返回總是爲一維數組。

由下面的例子可以看出,不管兩個數組是什麼形式,返回的都是一維數組。

import numpy as np

HJL = np.append([1,2,3],[[4,5,6],[7,8,9]])
print(HJL)
# 當axis無定義時,是橫向加成,返回總是爲一維數組。
#[1 2 3 4 5 6 7 8 9]

HXH = np.append([[1,2],[3,4]],[[5,6,7],[8,9,10]])
print(HXH)
# [ 1  2  3  4  5  6  7  8  9 10]

axis=0的情況

axis=0,表示針對第1維進行操作,可以簡單的理解爲,加在了行上。所以行數增加,列數不變。

由此可知,列數必須保持相同。

【axis=0到底稱作第0維還是第1維,我看各種說法都有,知道我在說什麼就好】

import numpy as np

DYX = np.zeros((1,8))
HXH = np.ones((3,8))
XH = np.append(DYX, HXH,axis=0)

#先展示原來的數組
print(DYX) #(1, 8)
#[[0. 0. 0. 0. 0. 0. 0. 0.]]

print(HXH) # (3,8)
"""
[[1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1.]]
"""
#組合後的結果
print(XH)
"""
[[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 = 0,在第一維上拼接,所以說,(1,8)和(3,8)就變成了(4,8)

axis=1的情況

拓展列,行數不變。行數需要相同。

import numpy as np

DYX = np.zeros((3,1))
HXH = np.ones((3,8))
XH = np.append(DYX, HXH,axis=1)

print(DYX) #(3,1)
"""
[[0.]
 [0.]
 [0.]]
"""

print(HXH) # (3,8)
"""
[[1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1.]]
"""

#最終結果:
print(XH)
"""
[[0. 1. 1. 1. 1. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1. 1. 1. 1. 1.]
 [0. 1. 1. 1. 1. 1. 1. 1. 1.]]
"""

print(XH.shape)  #(3, 9)
#axis = 1,在第二維上拼接,所以說,(3,1)和(3,8)就變成了(3,9)

axis=0和axis=1的圖示

 

axis=0或1時的多維數組我沒測試。因爲還沒用到,用到再說吧。

本篇完,如果錯誤,還望指正。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章