numpy.stack()
stack英文之意即為堆疊,故該函數的作用就是實現輸入數個數組不同方式的堆疊,返回堆疊后的1個數組
語法:numpy.stack(arrays,axis)
第一個參數arrays:用來作為堆疊的數個形狀維度相等的數組
第二個參數axis:即指定依照哪個維度進行堆疊,也就是指定哪種方式進行堆疊數組,常用的有0和1;
axis=0:意味着整體,對於0維堆疊,相當於簡單的物理羅列;如:
import numpy as np list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd', 'e'] list3 = [6, 7, 8, 9, 0] listAll = np.stack((list1, list2, list3), 0).tolist() print(listAll, type(listAll))
.tolist()輸出為列表,否則輸出為array;
直接堆疊,得到一個三行五列的二維列表,輸出結果:
[['1', '2', '3', '4', '5'], ['a', 'b', 'c', 'd', 'e'], ['6', '7', '8', '9', '0']] <class 'list'>
axis=1:意味着第一個維度,就是數組的每一行,相當於取每個數組的第一個元素(多維列表取第一行)進行堆疊為新列表的第一行,取第二個元素堆疊為新列表的第二行,依次類推;如:
import numpy as np list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd', 'e'] list3 = [6, 7, 8, 9, 0] listAll = np.stack([list1, list2, list3], 1).tolist() print(listAll, type(listAll))
得到一個五行三列的二維列表,輸出結果:
[['1', 'a', '6'], ['2', 'b', '7'], ['3', 'c', '8'], ['4', 'd', '9'], ['5', 'e', '0']] <class 'list'>