search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Flattening NumPy arrays

schedule Aug 11, 2023
Last updated
local_offer
PythonNumPy
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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:

``` x.flatten() 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] = 5print("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.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
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!