改变nparray的形状 [英] Change shape of nparray
问题描述
import numpy as np
image1 = np.zeros((120, 120))
image2 = np.zeros((120, 120))
image3 = np.zeros((120, 120))
pack1 = np.array([image1,image2,image3])
pack2 = np.array([image1,image2,image3])
result = np.array([pack1,pack2])
print result.shape
结果是: (2,3,120,120)
the result is : (2, 3, 120, 120)
问题:如何在不混合的情况下用相同的数据制作形状为(2,120,120,3)的数组?
Question : how can I make array with shape (2,120,120,3) with same data without mixing?
推荐答案
使用np.rollaxis
将单轴移动(确定,滚动)到指定位置:
Use np.rollaxis
to move (OK, roll) a single axis to a specified position:
>>> a.shape
(2, 3, 11, 11)
>>> np.rollaxis(a, 0, 4).shape
(3, 11, 11, 2)
这里的语法是滚动第0根轴,使其成为新数组中的第4根".
Here the syntax is "roll the zeroth axis so that it becomes the 4th in the new array".
请注意,rollaxis
创建了一个视图且未复制:
Notice that rollaxis
creates a view and does not copy:
>>> np.rollaxis(a, 0, 4).base is a
True
另一种方法(通常是更易读的方法)是使用np.transpose
接受将轴放置在何处的元组这一事实.观察:
An alternative (and often more readable) way would be to use the fact that np.transpose
accepts a tuple of where to place the axes. Observe:
>>> np.transpose(a, (1, 2, 3, 0)).shape
(3, 11, 11, 2)
>>> np.transpose(a, (1, 2, 3, 0)).base is a
True
这里的语法是对轴进行置换,以使原始数组中的第零个轴成为新数组中的第四个轴"
Here the syntax is "permute the axes so that what was the zeroth axis in the original array becomes the 4th axis in the new array"
这篇关于改变nparray的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!