Differences Between Flatten () and Ravel () | Numpy



We have two similar ways to convert ndarray to one-dimensional array: Flatten () and

# Python code for differentiation
# between Smooth and Ravel in NumPy

import numpy as np

 
# Create an empty array

a = np.array ([( 1 , 2 , 3 , 4 ), ( 3 , 1 , 4 , 2 )])

 
# Let`s print the array

print ( "Original array:"

print (a)

 
# To check the dimension of the array (dimension = 2) (and type numpy.ndarray)

print ( "Dimension of array- & gt; " , (a.ndim))

  

 

print ( "Output for RAVEL"

# Convert nd array to 1D array

b = a.ravel ()

 
# Ravel only passes a representation of the original array to an array & # 39; b & # 39;

print (b)

b [ 0 ] = 1000

print (b)

 
# Note that the value of the original array & # 39; a & # 39; when a [0] [0] becomes 1000

print (a)

 
# Just to check the dimension, i.e. 1 (and the type is the same numpy.ndarray)

print ( "Dimension of array- & gt;" , (b.ndim))

 

print ( " Output for FLATTEN "

  
# Convert nd array to 1D array

c = a.flatten ()

  
# Flatten transfers a copy of the original array in & # 39; c & # 39;

print (c)

c [ 0 ] = 0

print (c)

 
# Note that changing the value of c does not affect the value of the original array & # 39; a & # 39;

print (a)

 

print ( "Dimension of array- & gt; " , (c.ndim))

 OUTPUT: Original array: [[1 2 3 4] [3 1 4 2]] Dimension of array- & gt; 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- & gt; 1 

This article is courtesy of SHAURYA UPPAL .

Please , post comments if you find anything wrong, or if you would like to share more information on the topic discussed above.