Ndarray的Flatten()和Ravel()函数之间的区别

Ndarray的Flatten()和Ravel()函数之间的区别

将Ndarray转换为1D数组有两种方法,分别为flatten()和Ravel()

import numpy as nmp
P = nmp.array( [ (1,8,4,5),(4,3,5,1) ] )
#OUTPUT:
print( P.flatten() )
# [ 1,8,4,5,4,3,5,1 ] 
print ( P.ravel() )
# [ 1,8,4,5,4,3,5,1 ] 

这里的问题是,为什么在执行相同工作时有两个不同的角色?

Flatten() 和 Ravel() 的区别

P.ravel()

  1. 仅返回原始数组的引用/视图
  2. 如果我们修改数组,我们可以看到原始数组的值也会改变。
  3. Ravel比flatten()更快,因为它不占用任何内存。
  4. Ravel是库级别的函数。

P.flatten()

  1. 返回原始数组的副本
  2. 当你修改该数组的值时,原始数组的值不会改变。
  3. Flatten()比ravel()快很多,因为它占用内存。
  4. Flatten是一个由ndarray使用的方法。

让我们使用以下代码来了解flatter()和ravel()函数之间的区别。

代码:

import numpy as nmp

# Here, we will create a numpy array
P = nmp.array([(3,4,5,6),(5,3,6,7)])

# Now, we will print the array a
print ("Original array:\n ")
print(P)

# For checking the dimension of array (dimension = 2 and type is numpy.ndarray )
print ("Dimension of array: " , (P.ndim))


print("\n The output for RAVEL \n")
# Here, we will convert ndarray to 1D array
Q = P.ravel()

# As the ravel() only passes a view of the original array to array 'Q'
print(Q)
Q[0]=1000
print(Q)

# We can note here that value of the original array 'P' at also P[0][0] becomes 1000
print(P)

# Just for checking the dimension i.e. 1 and type is same numpy.ndarray )
print ("Dimension of array" ,(Q.ndim))

print("\n The output for FLATTEN \n")

# Here, we will convert ndarray to 1D array
R = P.flatten()

# Flatten passes copy of original array to 'R'
print(R)
R[0] = 0
print(R)

# Here, we can note that by changing the value of R 
# there is no affect on value of original array 'P'
print(P)

print ("Dimension of array " , (R.ndim))

输出:

Original array:

[[3 4 5 6]
 [5 3 6 7]]
Dimension of array:  2

 The output for RAVEL 

[3 4 5 6 5 3 6 7]
[1000    4    5    6    5    3    6    7]
[[1000    4    5    6]
 [   5    3    6    7]]
Dimension of array 1

 The output for FLATTEN 

[1000    4    5    6    5    3    6    7]
[0 4 5 6 5 3 6 7]
[[1000    4    5    6]
 [   5    3    6    7]]
Dimension of array  1

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程