python使用numpy.stack将多个数组组合成二维数组

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'>

 

posted @ 2021-11-25 14:34  童薰  阅读(4526)  评论(0编辑  收藏  举报