Table of Contents
ToggleFlattening arrays in NumPy refers to the process of converting multi-dimensional arrays into a one-dimensional array, where all elements are placed sequentially. This means that regardless of the dimensions (whether it’s a 2D, 3D, or higher-dimensional array), flattening reduces it to a single vector of elements.
NumPy provides two functions, ndarray.flatten() and ndarray.ravel(), both of which are used to flatten arrays.
The flatten() function in NumPy is used to convert multi-dimensional arrays into a one-dimensional array, also known as flattening.
It returns a new array that contains all the elements of the original array in a single row-major order (C-style) sequence. Following is the syntax −
arr.flatten(order='C')
Where, order is an optional parameter specifying the order of elements. Default is ‘C’ for row-major order.
In the below example, we are flattening an array “arr” in a single row-major order using the flatten() function in NumPy −
# Open Compiler
import numpy as np
# array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Flattening the array
flattened_arr = arr.flatten()
print("Original Array:")
print(arr)
print("\nFlattened Array:", flattened_arr)
Output:
Following is the output obtained −
Original Array:
[[1 2 3]
[4 5 6]]
Flattened Array: [1 2 3 4 5 6]
The ravel() function in NumPy is used to create a flattened 1D array from a multi-dimensional array. Unlike flatten() function, the ravel() function returns a flattened view of the original array without making a copy whenever possible. Following is the syntax −
arr.ravel(order='C')
In the example below, we are using the ravel() function to flatten a 2D array into a 1D array −
# Open Compiler
import numpy as np
# array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Flattening the array
raveled_arr = arr.ravel()
print("Original Array:")
print(arr)
print("\nRaveled Array:", raveled_arr)
Output:
Following is the output of the above code −
Original Array:
[[1 2 3]
[4 5 6]]
Raveled Array: [1 2 3 4 5 6]
When you flatten a multi-dimensional array in Fortran order, you convert it into a one-dimensional array where the elements are arranged as if you were reading the array column by column.
For example, if you have a 2D array A with dimensions (rows, columns), flattening it in Fortran order would arrange the elements such that you iterate over all elements in the first column, then move to the second column, and so on.
In NumPy, you can flatten an array in Fortran order by setting the order parameter to ‘F’ in the flatten() function.
In this example, we are flattening an array “arr” in Fortran order using the array.flatten() function in NumPy −
# Open Compiler
import numpy as np
# array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Flatten in Fortran order
flattened_arr_fortran = arr.flatten(order='F')
print("Original Array:")
print(arr)
print("\nFlattened Array (Fortran order):", flattened_arr_fortran)
Output:
After executing the above code, we get the following output −
Original Array:
[[1 2 3]
[4 5 6]]
Flattened Array (Fortran order): [1 4 2 5 3 6]
In NumPy, you can concatenate flattened arrays using the numpy.concatenate() function. Here is how you can do it step-by-step −
flatten() function. This converts each multi-dimensional array into a one-dimensional array.numpy.concatenate() function to concatenate the flattened arrays into a single array.Concatenation is the process of combining multiple arrays into one larger array. When you concatenate flattened arrays, you are mainly appending the elements of each flattened array one after another to create a single, longer array.
In the example below, we are first flattening 2D arrays “arr1” and “arr2” using the array.flatten() function. Then, we are concatenating these flattened arrays using the concatenate() function in NumPy −
# Open Compiler
import numpy as np
# arrays
arr1 = np.array([[1, 2],
[3, 4]])
arr2 = np.array([[5, 6],
[7, 8]])
# Flatten arrays
flat_arr1 = arr1.flatten()
flat_arr2 = arr2.flatten()
# Concatenate flattened arrays
concatenated_arr = np.concatenate((flat_arr1, flat_arr2))
print("Flattened Array 1:")
print(flat_arr1)
print("\nFlattened Array 2:")
print(flat_arr2)
print("\nConcatenated Flattened Array:", concatenated_arr)
Output:
The output obtained is as shown below −
Flattened Array 1:
[1 2 3 4]
Flattened Array 2:
[5 6 7 8]
Concatenated Flattened Array: [1 2 3 4 5 6 7 8]
Initializing a flattened array with zeros is a way of creating a one-dimensional array where all elements are set to zero.
NumPy provides a function numpy.zeros_like() to create an array of zeros with the same shape and type as a given array. Following is the syntax −
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)
Where,
a is used.a.shape.In this example, we are creating a 2D NumPy array “arr” initialized with specific values. We then flatten “arr” into a 1D array and initialize “flattened_zeros” with zeros −
# Open Compiler
import numpy as np
# Initializing a 2D array
arr = np.array([[1, 2],
[3, 4]])
# Flattening and initializing with zeros
flattened_zeros = np.zeros_like(arr.flatten())
print("Original Array:")
print(arr)
print("\nFlattened Array with Zeros:", flattened_zeros)
Output:
The result produced is as follows −
Original Array:
[[1 2]
[3 4]]
Flattened Array with Zeros: [0 0 0 0]
To find the maximum value in a flattened array means to determine the largest element within a one-dimensional representation of a multi-dimensional array.
In NumPy, you can find the maximum value in an array using the numpy.max() function. When applied to a flattened array, this function returns the highest value present in that array. Following is the syntax −
numpy.max(a, axis=None, out=None, keepdims=False, initial=None, where=True)
Where,
In the following example we are using the numpy.max() function to find the maximum value in a flattened array −
# Open Compiler
import numpy as np
# array
arr = np.array([[1, 2],
[3, 4]])
# Flatten array
flattened_arr = arr.flatten()
# Find maximum value
max_value = np.max(flattened_arr)
print("Original Array:")
print(arr)
print("\nFlattened Array:")
print(flattened_arr)
print("\nMaximum Value in Flattened Array:", max_value)
Output:
We get the output as shown below −
Original Array:
[[1 2]
[3 4]]
Flattened Array:
[1 2 3 4]
Maximum Value in Flattened Array: 4
Key Takeaway: Master flattening NumPy arrays effectively at Vista Academy!
