+2 votes
in Programming Languages by (17.0k points)

Multidimensional arrays can be flattened to a 1D array using either flatten() or ravel() function. What is the difference between these two functions?

1 Answer

0 votes
by (29.3k points)

The ravel() function actually creates a view of the parent array. This means that any changes to the new array affect the parent array as well. On the other hand, flatten() function creates a copy, so any changes in the new array do not affect the parent array. ravel() is also memory efficient as it does not create a copy.

Here is an example:
>>> import numpy as np
>>> x = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
>>> x
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> y1=x.flatten()
>>> y1
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
>>> y1[2]=100
>>> y1
array([  1,   2, 100,   4,   5,   6,   7,   8,   9,  10,  11,  12])
>>> x
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])


>>> y2=x.ravel()
>>> y2
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
>>> y2[2]=200
>>> y2
array([  1,   2, 200,   4,   5,   6,   7,   8,   9,  10,  11,  12])
>>> x
array([[  1,   2, 200,   4],
       [  5,   6,   7,   8],
       [  9,  10,  11,  12]])
...