
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
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