重点说一下 flatten() 和 ravel():
相同点:
两者的功能是一致的: 将多维数组将为一维数组
不同点:
在于是返回: 拷贝(copy) 还是 返回 视图(view)
numpy.flatten()返回一份拷贝,对拷贝所做的修改不会影响(reflects)原始矩阵,
而numpy.ravel()返回的是视图(view,有点类似 C/C++引用reference的意味),会影响(reflects)原始矩阵。
# 将多维数组将为一维数组
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.
>>> x = np.array([[1, 2], [3, 4]])
>>> x
array([[1, 2],
[3, 4]])
>>> x.flatten()
array([1, 2, 3, 4])
>>> x.ravel()
array([1, 2, 3, 4])
而且两者默认: 均是行序优先
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten() # 默认参数为"C",即按照行进行重组
array([1, 2, 3, 4])
>>> a.flatten('F') # 按照列进行重组
array([1, 3, 2, 4])
# ravel() 的两种用法:
# numpy.ravel()
>>> 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]
# ndarray.ravel(order='C)
>>> 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])
不同点:
>>> x = np.array([[1, 2], [3, 4]])
>>> x.flatten()[1] = 100
>>> x
array([[1, 2],
[3, 4]]) # flatten:返回的是 拷贝
>>> x.ravel()[1] = 100 # ravel : 返回的是 视图
>>> x
array([[ 1, 100],
[ 3, 4]])
reshape() 的用法:
# numpy.reshape(a, newshape, order='C')
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
# numpy.reshape()
>>> np.reshape(a, (2, 3))
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])
# ndarray.reshape()
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
>>> a.reshape(-1)
array([0, 1, 2, 3, 4, 5])
>>> a.T.reshape(-1) # 等同于flatten() 与 ravel() 按列将维
array([0, 2, 4, 1, 3, 5])
resize() 的用法:
# 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]])
flat 的用法:
>>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> list(x.flat)
[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]])