numpy 的stack 的直译是堆栈,通俗的说法就是如果你有一堆砖,您是横着放,还是竖着放。如果是3维空间,您是沿着x轴放,还是y轴放,还是z轴放。。。
stack的操作既可以对ndarray,又可以对list,但操作后,变量是ndarray.
我们先来验证对ndarray, 随机产生一个list嵌套array,变量名是arrays(type是list),但arrays的每一个元素都是ndarray。np.stack 操作以后,就是一个shape是(2,2,3)的ndarray。
import numpy as np
arrays = [np.random.randn(2,3) for _ in range(2)]
print("arrays in list is: {0}".format(arrays))
>arrays in list is: [array([[ 0.28396971, 0.92718814, -1.4422189 ],
[ 0.36319258, -0.61124134, -1.17067133]]),
array([[ 1.30923184, 0.6940435 , -0.2277809 ],
[-1.02785336, 0.18862084, -1.14111492]])]
print("type of arrays is: {0}".format(type(arrays)))
> type of arrays is: <class 'list'>
print("first element of list is array, {0}".format(type(arrays[0])))
> first element of list is array, <class 'numpy.ndarray'>
stack_arrays = np.stack(arrays,axis=0)
> stack_array is: [[[ 0.28396971 0.92718814 -1.4422189 ]
[ 0.36319258 -0.61124134 -1.17067133]]
[[ 1.30923184 0.6940435 -0.2277809 ]
[-1.02785336 0.18862084 -1.14111492]]]
print("type of stack_arrays is: {0}".format(type(stack_arrays)))
> type of stack_arrays is: <class 'numpy.ndarray'>
print("shape of arrays_stack is: {0}".format(stack_arrays.shape))
> shape of arrays_stack is: (2, 2, 3)
然后我们来验证list中嵌套list,看如下变量list_list, np.stack 对list_list操作后,stack_list的type变成了ndarray.
list_list = [
[[1,3,3],
[2,4,5]],
[[2,3,4],
[4,5,6]]]
print("type of list_list is: {0}".format(type(list_list)))
> type of list_list is: <class 'list'>
stack_list = np.stack(list_list,axis=0)
print("stack_list is :{0}".format(stack_list))
> stack_list is :[[[1 3 3]
[2 4 5]]
[[2 3 4]
[4 5 6]]]
print("type of stack_list is: {0}".format(type(stack_list)))
> type of stack_list is: <class 'numpy.ndarray'>