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

NumPy | reshape method

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!

NumPy's `reshape(~)` method returns a new NumPy array with the desired shape. If the reshaped array contains more values than the original array, then numbers will be repeated.

Parameters

1. `a` | `array-like`

The input array.

2. `shape` | `int` or `tuple` of `int`

The desired shape. If `-1` is passed, then the shape is inferred. Check our examples below for clarification.

Return value

A new NumPy array with the desired shape.

Examples

Converting from 1D to 2D

Consider the following 1D array:

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

To change this to a 2D array with 2 rows and 3 columns:

``` np.reshape(a, (2,3)) array([[1, 2, 3], [4, 5, 6]]) ```

To convert a 1D array to a 2D array with one element:

``` np.reshape(a, (1, a.size)) array([[1, 2, 3, 4, 5, 6]]) ```

Converting from 2D to 1D

Suppose we have the following 2D array:

``` a = np.array([[1,2],[3,4]])a array([[1, 2],       [3, 4]]) ```

To obtain the 1D representation:

``` np.reshape(a, 4) array([1, 2, 3, 4]) ```

Here, we could simply use the `ravel(~)` method to flatten the array:

``` a = np.array([[1,2],[3,4]])a.ravel() array([1, 2, 3, 4]) ```

Inferring the shape

The value `-1` in `shape` tells NumPy to infer the suitable shape. For instance:

``` np.reshape([1,2,3,4], [-1,1]) array([[1], [2], [3], [4]]) ```

We could have manually specified `[4,-1]` as the shape, but the number of resulting rows can be inferred from:

• the number of values there are in the array

• the number of columns (`1` in this case).

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!