numpy.stack()函数用于沿新轴连接相同尺寸数组的序列。axis参数指定结果轴尺寸中新轴的索引。例如,如果axis = 0,它将是第一个尺寸;如果axis = -1,它将是最后的尺寸。
用法: numpy.stack(arrays, axis)
参数:
arrays :[数组]相同形状的数组序列。
axis :[int]输入数组沿其堆叠的结果数组中的轴。
Return :[stacked ndarray]输入数组的堆栈数组,其维数比输入数组大。
代码1:
# Python program explaining
# stack() function
import numpy as geek
# input array
in_arr1 = geek.array([ 1, 2, 3] )
print ("1st Input array:\n", in_arr1)
in_arr2 = geek.array([ 4, 5, 6] )
print ("2nd Input array:\n", in_arr2)
# Stacking the two arrays along axis 0
out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)
print ("Output stacked array along axis 0:\n ", out_arr1)
# Stacking the two arrays along axis 1
out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)
print ("Output stacked array along axis 1:\n ", out_arr2)
输出:
1st Input array: [1 2 3] 2nd Input array: [4 5 6] Output stacked array along axis 0: [[1 2 3] [4 5 6]] Output stacked array along axis 1: [[1 4] [2 5] [3 6]]
代码2:
# Python program explaining
# stack() function
import numpy as geek
# input array
in_arr1 = geek.array([[ 1, 2, 3], [ -1, -2, -3]] )
print ("1st Input array:\n", in_arr1)
in_arr2 = geek.array([[ 4, 5, 6], [ -4, -5, -6]] )
print ("2nd Input array:\n", in_arr2)
# Stacking the two arrays along axis 0
out_arr1 = geek.stack((in_arr1, in_arr2), axis = 0)
print ("Output stacked array along axis 0:\n ", out_arr1)
# Stacking the two arrays along axis 1
out_arr2 = geek.stack((in_arr1, in_arr2), axis = 1)
print ("Output stacked array along axis 1:\n ", out_arr2)
# Stacking the two arrays along last axis
out_arr3 = geek.stack((in_arr1, in_arr2), axis = -1)
print ("Output stacked array along last axis:\n ", out_arr3)
输出:
1st Input array: [[ 1 2 3] [-1 -2 -3]] 2nd Input array: [[ 4 5 6] [-4 -5 -6]] Output stacked array along axis 0: [[[ 1 2 3] [-1 -2 -3]] [[ 4 5 6] [-4 -5 -6]]] Output stacked array along axis 1: [[[ 1 2 3] [ 4 5 6]] [[-1 -2 -3] [-4 -5 -6]]] Output stacked array along last axis: [[[ 1 4] [ 2 5] [ 3 6]] [[-1 -4] [-2 -5] [-3 -6]]]
相关用法
注:本文由纯净天空筛选整理自jana_sayantan大神的英文原创作品 numpy.stack() in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。