search
Search
Publish
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
chevron_left Cookbooks
Accessing a value in a 2D arrayAccessing columns of a 2D arrayAccessing rows of a 2D arrayCalculating the determinant of a matrixChecking allowed values for a NumPy data typeChecking if a NumPy array is a view or copyChecking the version of NumPyChecking whether a NumPy array contains a given rowComputing Euclidean distance using NumpyConcatenating 1D arraysConverting array to lowercaseConverting type of NumPy array to stringCreating a copy of an arrayDifference between Python List and Numpy arrayDifference between the methods array_equal and array_equivDifference between the methods mod and fmodDifference between the methods power and float_powerFinding the closest value in an arrayFinding the Index of Largest Value in a Numpy ArrayFinding the Index of Smallest Value in a Numpy ArrayFinding the most frequent value in a NumPy arrayFlattening Numpy arraysGetting constant PiGetting elements from a two dimensional array using two dimensional array of indicesGetting indices of N maximum valuesGetting indices of N minimum valuesGetting the number of columns of a 2D arrayGetting the number of non-zero elements in a NumPy arrayGetting the number of rows of a 2D arrayInitializing an array of onesInitializing an array of zerosInitializing an identity matrixLimiting array values to a certain rangePerforming linear regressionPrinting full or truncated NumPy arrayPrinting large Numpy arrays without truncationRemoving rows containing NaN in a NumPy arrayReversing a NumPy arraySaving NumPy array to a fileShape of Numpy ArraysSorting value of one array according to anotherSuppressing scientific notation
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe: "Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
share
thumb_up_alt
bookmark
arrow_backShare
Twitter
Facebook
chevron_left Cookbooks
Accessing a value in a 2D arrayAccessing columns of a 2D arrayAccessing rows of a 2D arrayCalculating the determinant of a matrixChecking allowed values for a NumPy data typeChecking if a NumPy array is a view or copyChecking the version of NumPyChecking whether a NumPy array contains a given rowComputing Euclidean distance using NumpyConcatenating 1D arraysConverting array to lowercaseConverting type of NumPy array to stringCreating a copy of an arrayDifference between Python List and Numpy arrayDifference between the methods array_equal and array_equivDifference between the methods mod and fmodDifference between the methods power and float_powerFinding the closest value in an arrayFinding the Index of Largest Value in a Numpy ArrayFinding the Index of Smallest Value in a Numpy ArrayFinding the most frequent value in a NumPy arrayFlattening Numpy arraysGetting constant PiGetting elements from a two dimensional array using two dimensional array of indicesGetting indices of N maximum valuesGetting indices of N minimum valuesGetting the number of columns of a 2D arrayGetting the number of non-zero elements in a NumPy arrayGetting the number of rows of a 2D arrayInitializing an array of onesInitializing an array of zerosInitializing an identity matrixLimiting array values to a certain rangePerforming linear regressionPrinting full or truncated NumPy arrayPrinting large Numpy arrays without truncationRemoving rows containing NaN in a NumPy arrayReversing a NumPy arraySaving NumPy array to a fileShape of Numpy ArraysSorting value of one array according to anotherSuppressing scientific notation
thumb_up
0
thumb_down
0
chat_bubble_outline
0
auto_stories new
settings

Flattening NumPy arrays

Programming
chevron_right
Python
chevron_right
NumPy
chevron_right
Cookbooks
schedule Jul 1, 2022
Last updated
local_offer PythonNumPy
Tags
tocTable of Contents
expand_more

We can reduce a n-dimensional NumPy array to 1D using either the flatten() or ravel() method available to all NumPy arrays. We first demonstrate their usages, and subsequently their differences.

Example

Consider the following 2 by 3 array:

x = np.array([[1,2,3],[4,5,6]])
array([[1, 2, 3],
[4, 5, 6]])

We can use the flatten method as follows:

array([1, 2, 3, 4, 5, 6])

We can also use the ravel method:

x.ravel()
array([1, 2, 3, 4, 5, 6])

Notice the outputs are the same - we end up with a one-dimensional flattened array.

Difference between flatten and ravel

The flatten(~) returns a separate copy of the NumPy array. This means that making modification on the original array would not have any impact on the flattened array. Just to illustrate, study the following code:

x = np.array([1,2,3])
y = x.flatten()
y[0] = 5
print("x:", x)
print("y:", y)
x: [1 2 3]
y: [5 2 3]

On the other hand, the ravel(~) returns a NumPy array that shares the same memory address as the original array:

x = np.array([[1,2,3],[4,5,6]])
y = x.ravel()
print(y) # [1 2 3 4 5 6]
x[0,0] = 9
print(x) # [[9 2 3] [4 5 6]]
print(y) # [9 2 3 4 5 6]

As arrays x and y both share the same memory address, when we update value [0,0] in array x, we can see that the new assignment of 9 is reflected in array y also.

In terms of speed and memory-savings, ravel() is superior. Therefore, use ravel() if you are certain that:

  • you won't need the original array

  • you won't make any modification on the original array

You should also be reminded that, unless we are dealing with large amounts of data, the performance difference is negligible. Therefore, you may want to use flatten() to ensure that nothing out of the ordinary happens.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!