r Numpy中Flatten() 和 Ravel()函数的区别

Numpy中有两种将 ndarray 转换为一维数组类似的方法: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() 的区别:

a.ravel():

  • 只返回原始数组的引用/视图
  • 如果修改数组,就会注意到原始数组的值也会发生变化。
  • Ravel() 比 flatten() 更快,因为它不占用任何内存。
  • Ravel() 是一个库级函数。

a.flatten() :

  • 返回原始数组的副本;
  • 如果您修改此数组的任何值,原始数组的值不受影响。
  • 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))

运行结果如下:

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
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明:文章转载自 有区别网 [http://www.vsdiffer.com]
本文标题:Numpy中Flatten() 和 Ravel()函数的区别
本文链接:https://www.vsdiffer.com/vs/differences-flatten-ravel-numpy.html
免责声明:以上内容仅是站长个人看法、理解、学习笔记、总结和研究收藏。不保证其正确性,因使用而带来的风险与本站无关!如本网站内容冒犯了您的权益,请联系站长,邮箱: ,我们核实并会尽快处理。