[NumPy] reshape(), resize()

Approches to transform the shape of ndarray

numpy.reshape(array, (shape), order = 'C')
transform [8, 1] to [2, 4]
import numpy as nparrayA = np.arange(8)# arrayA = array([0, 1, 2, 3, 4, 5, 6, 7])np.reshape(arrayA, (2, 4))# array([[0, 1, 2, 3],        [4, 5, 6, 7]])

If the number of elements is not same between input and output, raise ValueError

numpy.reshape(array, (shape), order = 'F')
np.reshape(arrayA, (2, 4), order = 'F')# array([[0, 2, 4, 6],        [1, 3, 5, 7]])
ndarray.reshape()
arrayB = arrayA.reshape(2, 4)

ndarray.reshape() doesn't change the data from original matrix, it returns the modified one

numpy.resize()
arrayA = np.arange(8)arrayB = arrayA.resize(arrayA, (2, 4))# array([[0, 1, 2, 3],         [4, 5, 6, 7]])
arrayC = np.resize(arrayA, (3, 4))arrayC# array([[0, 1, 2, 3],         [4, 5, 6, 7],         [0, 1, 2 ,3]])

If the new size is larger than the original one, it will repeat the elements to fill the spaces.


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章