Flatten and ravel in numpy| Data Science tutorial| codin india

 Sometimes when we have a multidimensional array and we want to collapse it to single Dimensional array, we can use either flatten() and ravel() method.

Let us understand by code and how to use it in our program.

Code:- 

Flatten numpy





Output:- 





In this case, we will create 2-D array and after that we use flatten() and ravel() methods.

flatten and ravel will convert 2-D Array into 1-D array.

NOTE:- But an important note is that the flatten() returns the copy of the original array while the ravel() returns a reference of the original array.

This means any changes made to the array returned from ravel() will also be reflected in the original array while this will not be in case with flatten().

It is concept of Deep copy and Shallow copy.

Let us understand by the code:-

Deep copy and shallow copy






Output:-

code of flatten and ravel





In this case, first we change the value from flatten and then print the original value.

From this example, you will definitely understand flatten and deep copy.


What are Deep copy and shallow copy?

What happened here is that the Flatten() creates a Deep Copy of the nd-array while Ravel() creates a Shallow Copy of nd-array.

Deep Copy:-

It means that a completely new array is created in memory and the new array object returned by Flatten() is now pointing to the new memory location. Therefore any changes made here will not be reflected to orignal Array.

Flatten() is an example of Deep Copy.


Shallow Copy:-

A shallow copy, on the other hand, returns a reference to the original memory location. That means object returned by the Ravel() is pointing to the same memory location as the original nd-array object. So definitely, any changes made to this array will also be reflected in the original array too.


I hope you liked this Post:)

Comments