NumPy - Flattening Arrays
Flattening NumPy Array
Flattening arrays in NumPy refers to the process of converting a 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 is used to flatten arrays.
Flattening Arrays Using flatten() Function
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.
Example
In the below example, we are flattening an array “arr” in a single row-major order using the flatten() function in NumPy −
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)
Following is the output obtained −
Original Array:
[[1 2 3]
[4 5 6]]
Flattened Array: [1 2 3 4 5 6]
Flattening Arrays Using ravel() Function
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')
Example
In the example below, we are using the ravel() function to flatten a 2D array into a 1D array −
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)
Following is the output of the above code −
Original Array:
[[1 2 3]
[4 5 6]]
Raveled Array:[1 2 3 4 5 6]
Flattening Array in Fortran Order
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.
Example
In this example, we are flattening an array “arr” in Fortran order using the array.flatten() function in NumPy −
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)
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]
Concatenating Flattened Arrays
In NumPy, you can concatenate flattened arrays using the numpy.concatenate() function. Here is how you can do it step-by-step −
- Flatten Arrays − First, you need to flatten each array that you want to concatenate using the flatten() function. This converts each multi-dimensional array into a one-dimensional array.
- Concatenate − Then, use the 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.
Example
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 −
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)
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
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 − It is the input array.
- dtype (optional) − It specifies the data type of the output array. If not provided, the data type of a is used.
- order (optional) − It specifies the memory layout order of the result (‘C’ for row-major, ‘F’ for column-major, ‘A’ for any, ‘K’ for keep, ‘C’ is default).
- subok (optional) − If True, then sub-classes will be passed-through, otherwise, the returned array will be forced to be a base-class array (default).
- shape (optional) − It is the shape of the output array. If not given, it defaults to a.shape.
Example
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 −
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)
The result produced is as follows −
Original Array:
[[1 2]
[3 4]]
Flattened Array with Zeros: [0 0 0 0]
Finding Maximum Value in Flattened Array
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,
- a − It is the input array for which you want to compute the maximum value.
- axis (optional) − It specifies the axis along which to operate. By default “None” is returned as the maximum value of the flattened array.
- out (optional) − It is the output array where the result is stored. If provided, it must have the same shape and buffer length as the expected output.
Example
In the following example we are using the numpy.max() function to find the maximum value in a flattened array −
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)
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