ndarray.flatten(order='C')
将数组变为一维
Parameters: order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
‘C’ means to flatten in row-major (C-style) order.
‘F’ means to flatten in column-major (Fortran- style)
order. ‘A’ means to flatten in column-major order if
a is Fortran contiguous in memory, row-major order
otherwise. ‘K’ means to flatten a in the order the
elements occur in memory. The default is ‘C’.
Returns: y : ndarray
A copy of the input array, flattened to one
dimension.
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten() # 默认参数为"C",即按照行进行重组
array([1, 2, 3, 4])
>>> a.flatten('F') # 按照列进行重组
array([1, 3, 2, 4])
>>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x.flat[3] # 返回重组后的一维数组下标为3的元素
4
>>> x.T
array([[1, 4],
[2, 5],
[3, 6]])
>>> x.T.flat[3] # 返回x的转置重组后的一维数组下标为3的元素
5
>>> x.flat = 3 # 将数组的元素均变为3
>>> x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1 # 将数组重组后的一维数组小标为1,4的元素变为1
>>> x
array([[3, 1, 3],
[3, 1, 3]])
numpy.ravel
numpy.ravel(a, order='C')
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> y = np.ravel(x) # 默认order="C",按照行进行重组
>>> y
[1 2 3 4 5 6]
>>> y = np.ravel(x, order='F') # 按照列进行重组
>>> y
[1 4 2 5 3 6]
>>> a = np.arange(12).reshape(2,3,2).swapaxes(1,2)
>>> a
array([[[ 0, 2, 4],
[ 1, 3, 5]],
[[ 6, 8, 10],
[ 7, 9, 11]]])
>>> a.ravel(order='C')
array([ 0, 2, 4, 1, 3, 5, 6, 8, 10, 7, 9, 11])
>>> a.ravel(order='K')
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
numpy.reshape(a, newshape, order='C')
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
>>> np.reshape(a, (2, 3))
array([[0, 1, 2],
[3, 4, 5]])
>>> a.reshape(-1)
array([0, 1, 2, 3, 4, 5])
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
numpy.resize
>>> a=np.array([[0,1],[2,3]])
>>> np.resize(a,(2,3))
array([[0, 1, 2],
[3, 0, 1]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
[0, 1, 2, 3]])
ndarray.resize
>>> b = np.array([[0, 1], [2, 3]])
>>> b.resize(2, 3)
>>> b
array([[0, 1, 2],
[3, 0, 0]])
>>> b.resize(1,4)
array([[0, 1, 2, 3]])
>>> b.resize(2,4)
array([[0, 1, 2, 3],
[0, 0, 0, 0]])
请注意上述两者之间的区别,numpy.resize重组数据不够时,使用原数据依次填补;ndarray.resize重组数据不够时,使用原数据第一个元素填补。