Convert data to one dimension
Prepare multidimensional data for APIs or algorithms that require a single sequence.
NumPy · Function
Flatten an array-like input into a contiguous one-dimensional array. The reading order is configurable, and copying occurs only when needed.
np.ravel reads an input array in the requested index order and produces a contiguous one-dimensional array. It can reuse the input storage when possible, but creates a copy when contiguity or the requested ordering requires it.
numpy.ravel(a, order='C')| Name | Type | Description |
|---|---|---|
a | array_like | Input array or array-like object whose elements will be flattened. |
order | {'C', 'F', 'A', 'K'}, optional | Indexing order used to read the input: 'C', 'F', 'A', or 'K'. It defaults to 'C'. |
A contiguous one-dimensional array of the same subtype as a, with shape (a.size,).
import numpy as np
a = np.array([[1, 2], [3, 4]])
print(np.ravel(a)) # [1 2 3 4]
print(np.ravel(a, order="F")) # [1 3 2 4]Flatten a two-dimensional array using the default row-major order and then column-major order.
Prepare multidimensional data for APIs or algorithms that require a single sequence.
Choose row-major or column-major traversal before serialization or processing.
Reduce unnecessary allocation when a contiguous view can satisfy the requested layout.
np.ravel returns a contiguous one-dimensional array containing all input elements. It makes a copy only when necessary, so it may be more memory-efficient than an operation that always copies.
Follow-up: How does order='K' differ from order='C'? order='K' follows the elements' memory layout, while order='C' uses row-major indexing regardless of the layout.
The order argument controls how elements are read before they are packed into one dimension. 'C' uses row-major order, 'F' uses column-major order, 'A' chooses Fortran-like order for Fortran-contiguous input and C-like order otherwise, and 'K' follows memory order.
Follow-up: Which order should be used to preserve the physical traversal of an array? Use 'K', subject to its documented handling of negative strides.
The result is a contiguous one-dimensional array with shape (a.size,). It has the same subtype as the input array, preserving ndarray subclasses where applicable.
Follow-up: Does flattening change the number of elements? No. It changes the shape to one dimension while retaining a total element count equal to the input's size.
numpy.ndarray.flattennumpy.reshapenumpy.ndarray.ravel