python学习笔记之-展平函数ravel和flatten及两者的区别

ravel()flatten()是将多维数据展平为一维数据,功能相同,区别在于一个是引用操作,一个是复制操作。ravel()展平数据后,修改后面的数据会影响前面的数据,而flatten()展平数据后,不会影响前面的数据。

代码如下:

import numpy as np

a = np.arange(15).reshape(3,5)
a
>>> array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

# ravel()方法
b = a.ravel()
b
>>> array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

# flatten()方法
c = a.flatten()
c
>>> array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

# 修改b
b[1] = 321
a
>>> array([[  0, 321,   2,   3,   4],
       [  5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14]])

# 修改c前
c
>>> array([  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

# 此时a
a
>>> array([[  0, 321,   2,   3,   4],
       [  5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14]])

# 修改c后
c[2] = 456
c
>>> array([  0,   1, 456,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,
        13,  14])

# 此时a
a
>>> array([[  0, 321,   2,   3,   4],
       [  5,   6,   7,   8,   9],
       [ 10,  11,  12,  13,  14]])

你可能感兴趣的:(python学习笔记,python,numpy,展平函数,多维数据转一维数据)