numpy库ndarray多维数组的维度变换方法(reshape、resize、swapaxes、flatten)
(编辑:jimmy 日期: 2024/11/18 浏览:3 次 )
numpy库对多维数组有非常灵巧的处理方式,主要的处理方法有:
.reshape(shape) : 不改变数组元素,返回一个shape形状的数组,原数组不变
.resize(shape) : 与.reshape()功能一致,但修改原数组
In [22]: a = np.arange(20) #原数组不变 In [23]: a.reshape([4,5]) Out[23]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) In [24]: a Out[24]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) #修改原数组 In [25]: a.resize([4,5]) In [26]: a Out[26]: array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]])
.swapaxes(ax1,ax2) : 将数组n个维度中两个维度进行调换,不改变原数组
In [27]: a.swapaxes(1,0) Out[27]: array([[ 0, 5, 10, 15], [ 1, 6, 11, 16], [ 2, 7, 12, 17], [ 3, 8, 13, 18], [ 4, 9, 14, 19]])
.flatten() : 对数组进行降维,返回折叠后的一维数组,原数组不变
In [29]: a.flatten() Out[29]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
下一篇:python中sympy库求常微分方程的用法