Python——数组重组(flatten
短信预约 -IT技能 免费直播动态提醒
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重组数据不够时,使用原数据第一个元素填补。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341