numpy中函数resize与reshape,ravel与flatten的区别

这两组函数中区别很是类似,都是一个不改变之前的数组,一个改变数组本身

resize和reshape

>>> import numpy as np
>>> a = np.arange(20).reshape(4,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> a.reshape(2,10)
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> a.resize(2,10)
>>> a
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])

两个函数都是改变数组的形状,但是resize是在本身上进行操作,reshape返回的是修改之后的参数


ravel和flatten

两者都可以将数组转换为一个维,

flatten(order='C')
参数:{‘C’,‘F’,‘A’,‘K’}

默认情况下‘C’以行为主的顺序展开,‘F’(Fortran风格)意味着以列的顺序展开,‘A’表示如果a在内存中为Fortran连续,则按列展开,否则以行展开,‘K’按照元素在内存中出现的顺序展平a

>>> a = np.arange(6).reshape(2,3)
>>> a.flatten()
array([0, 1, 2, 3, 4, 5])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5])
>>> a.flatten('F')
array([0, 3, 1, 4, 2, 5])
>>> a.ravel('F')
array([0, 3, 1, 4, 2, 5])
>>> 
>>> x = np.array([[1,2],[3,4]])
>>> a = np.arange(6).reshape(2,3)
>>> a.flatten()[...] = 1
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> a.ravel()[...] = 1
>>> a
array([[1, 1, 1],
       [1, 1, 1]])
>>> 
flatten不会影响原始矩阵,返回的是一个副本,但是ravel是会修改数组

你可能感兴趣的:(python3)