Numpy中Flatten()和Ravel()函数的区别
我们有两种类似的方法将ndarray数组转换为1D数组:Flatten()和Ravel()
import numpy as np
a = np.array( [ (1,7,3,4),(3,2,4,1) ] )
#OUTPUT:
print( a.flatten() )
# [ 1,7,3,4,3,2,4,1 ]
print ( a.ravel() )
# [ 1,7,3,4,3,2,4,1 ]
这里出现了一个问题,为什么有两个numpy函数来完成相同的任务?
Flatten()和Ravel()的区别
.ravel ():
(i)只返回原始数组的引用/视图
(ii)如果你修改数组,你会注意到原始数组的值也改变了。
(iii) Ravel比flatten()更快,因为它不占用任何内存。
(iv) Ravel是一个图书馆级的功能。
.flatten ():
(i)返回原数组的副本
(ii)如果修改此数组的任何值,原数组的值都不受影响。
(iii) Flatten()比ravel()要慢一些,因为它占用内存。
Flatten是一个ndarray对象的方法。
让我们通过这段代码来检查区别
# Python code to differentiate
# between flatten and ravel in numpy
import numpy as np
# Create a numpy array
a = np.array([(1,2,3,4),(3,1,4,2)])
# Let's print the array a
print ("Original array:\n ")
print(a)
# To check the dimension of array (dimension =2)
# ( and type is numpy.ndarray )
print ("Dimension of array-> " , (a.ndim))
print("\nOutput for RAVEL \n")
# Convert nd array to 1D array
b = a.ravel()
# Ravel only passes a view of
# original array to array 'b'
print(b)
b[0]=1000
print(b)
# Note here that value of original
# array 'a' at also a[0][0] becomes 1000
print(a)
# Just to check the dimension i.e. 1
# (and type is same numpy.ndarray )
print ("Dimension of array->" ,(b.ndim))
print("\nOutput for FLATTEN \n")
# Convert nd array to 1D array
c = a.flatten()
# Flatten passes copy of
# original array to 'c'
print(c)
c[0]=0
print(c)
# Note that by changing
# value of c there is no
# affect on value of original
# array 'a'
print(a)
print ("Dimension of array-> " , (c.ndim))
OUTPUT:
Original array:
[[1 2 3 4]
[3 1 4 2]]
Dimension of array-> 2
Output for RAVEL
[1 2 3 4 3 1 4 2]
[1000 2 3 4 3 1 4 2]
[[1000 2 3 4]
[ 3 1 4 2]]
Dimension of array-> 1
Output for FLATTEN
[1000 2 3 4 3 1 4 2]
[0 2 3 4 3 1 4 2]
[[1000 2 3 4]
[ 3 1 4 2]]
Dimension of array-> 1