如何将numpy数组的两个数组轴折叠在一起?

时间:2019-04-06 08:06:53

标签: python arrays numpy concatenation

基本思想:我有一组图像images=np.array([10, 28, 28, 3])。因此,具有3个颜色通道的10张图像28x28像素。我想将它们拼接成一条长线:single_image.shape # [280, 28, 3]。最好的基于numpy的函数是什么?

更笼统地说:是否有沿stitch(array, source_axis=0, target_axis=1)行的函数,该函数通过沿{{1}并置子数组A.shape # [a0, a1, source_axis, a4, target_axis, a6]将数组B.shape # [a0, a1, a4, target_axis*source_axis, a6]转换成形状A[:,:,i,:,:,:] }

2 个答案:

答案 0 :(得分:1)

这是我的看法:

def merge_axis(array, source_axis=0, target_axis=1):
    array = np.moveaxis(array, source_axis, 0)
    array = np.moveaxis(array, target_axis, 1)
    array = np.concatenate(array)
    array = np.moveaxis(array, 0, target_axis-1)
    return array

答案 1 :(得分:1)

您可以使用单个onTap + moveaxis组合键进行设置-

reshape

或者,def merge_axis(array, source_axis=0, target_axis=1): shp = a.shape L = shp[source_axis]*shp[target_axis] # merged axis len out_shp = np.insert(np.delete(shp,(source_axis,target_axis)),target_axis-1,L) return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp) 可以通过数组操作来设置,并且可能更容易遵循,就像这样-

out_shp

如果shp = np.array(a.shape) shp[target_axis] *= shp[source_axis] out_shp = np.delete(shp,source_axis) source的轴是相邻的,我们可以跳过target并简单地重塑形状,额外的好处是输出将是输入的视图,因此实际上运行时免费。因此,我们将引入一个If条件,以检查并修改我们的实现,使其类似于以下内容-

moveaxis

验证def merge_axis_v1(array, source_axis=0, target_axis=1): shp = a.shape L = shp[source_axis]*shp[target_axis] # merged_axis_len out_shp = np.insert(np.delete(shp,(source_axis,target_axis)),target_axis-1,L) if target_axis==source_axis+1: return a.reshape(out_shp) else: return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp) def merge_axis_v2(array, source_axis=0, target_axis=1): shp = np.array(a.shape) shp[target_axis] *= shp[source_axis] out_shp = np.delete(shp,source_axis) if target_axis==source_axis+1: return a.reshape(out_shp) else: return np.moveaxis(a,source_axis,target_axis-1).reshape(out_shp) -

views