Reshaping And Flattening Multidimensional Arrays?


Reshaping And Flattening Multidimensional Arrays?

Table Of Contents:

  1. arr.flatten()
  2. Examples Of arr.flatten()
  3. arr.ravel()
  4. Examples Of arr.ravel()

(1) arr.flatten()

  • Return a copy of the array collapsed into one dimension.

Syntax:

ndarray.flatten(order='C')

Parameters:

  • order: {‘C’, ‘F’, ‘A’, ‘K’}, optional – ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.

Returns:

  • y: ndarray – A copy of the input array, flattened to one dimension.

(2) Examples Of arr.flatten()

Example-1:

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]])
x.flatten()
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Example-2:

  • When you use flatten, changes to your new array won’t change the parent array.
a1 = x.flatten()
a1
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
a1[0] = 99
x  # Original array
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
a1
[99  2  3  4  5  6  7  8  9 10 11 12]

(2) arr.flatten()

  • Return a copy of the array collapsed into one dimension.

Syntax:

ndarray.ravel([order])

Returns:

  • y: ndarray – A copy of the input array, flattened to one dimension.

Example-1:

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]])
x.ravel()
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

Example-2:

  • But when you use ravel, the changes you make to the new array will affect the parent array.
a1 = x.ravel()
a1
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])
a1[0] = 99
x  # Original array
array([[99,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
a1
[99  2  3  4  5  6  7  8  9 10 11 12]

Leave a Reply

Your email address will not be published. Required fields are marked *