numpy.ravel() 与 numpy.flatten()

两者都可实现将多维数组降位一维的功能

numpy.flatten()返回拷贝,对拷贝所做的修改不会影响原始矩阵

numpy.ravel()返回视图,会影响原始矩阵

1)ravel()
In [16]: data                                                                  
Out[16]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [17]: data2 = data.ravel()        #ravel()                                          

In [18]: data2                                                                 
Out[18]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [19]: data2[0] = 99                                                         

In [20]: data2                                                                 
Out[20]: array([99,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [21]: data                                                                  
Out[21]: 
array([[99,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
2)flatten()
In [30]: data                                                                  
Out[30]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

In [31]: data2= data.flatten()   #flatten()                                              

In [32]: data2                                                                 
Out[32]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [33]: data2[0]=99                                                           

In [34]: data2                                                                 
Out[34]: array([99,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])

In [35]: data                                                                  
Out[35]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

 

posted @ 2019-03-31 15:11  西瓜草莓甘蔗  阅读(418)  评论(0编辑  收藏  举报