search
Search
Publish
Guest 0reps
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
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
A
A
share
thumb_up_alt
bookmark
arrow_backShare Twitter Facebook

# Shape of NumPy Arrays

Programming
chevron_right
Python
chevron_right
NumPy
chevron_right
Cookbooks
schedule Mar 9, 2022
Last updated
local_offer PythonNumPy
Tags

# Introduction

The `shape` property of a NumPy array is a tuple that tells us the size of the each nested array. This property is most commonly used to access the number of rows and columns of a 2D NumPy array.

# Example

## Get number of rows and columns of a 2D array

We want to get the number of rows and columns of a 2D NumPy array. The code is straight-forward:

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

Here, our NumPy array `x` has 2 rows and 3 columns.

## Extracting the values from the shape property

Since `shape` is a tuple, we can access the values using array-like notation:

``` num_rows = x.shapenum_cols = x.shapeprint("Number of rows: " + str(num_rows))print("Number of columns: " + str(num_cols)) Number of rows: 2Number of columns: 3 ```

# Misconceptions

## Shape of a 1D array

The shape of a 1D array can be a source of confusion for those who think of NumPy arrays as vectors/matrices.

### Example

Suppose we have the following code snippet:

``` x = np.array([1,2,3])x.shape (3,) ```

Somewhat confusingly, the presence of the comma may deceive you into thinking our `x` is two-dimensional. However, we know that `x` is one-dimensional as it's simply `[1,2,3]`. Therefore, if you see `,` followed by nothing, you have yourself a flattened array, or a vector for the mathematically-inclined. In addition, the `(3,)` just means that you have 3 elements in your array, and it has nothing to do with the number of rows and columns.

WARNING

Rows/Column interpretation only work for 2D arrays. The catch is that the `shape` property can be interpreted as the number of rows and columns for 2D arrays only. If we think of `np.array([1,2,3])` as a vector, or a 3 by 1 matrix, we may be inclined to think of its shape as `(3,1)`. While thinking in terms of vectors and matrices is helpful in the world of NumPy, we still need to keep in mind the subtlety of the shape property. The shape property gives us the size of the array in each of its dimension, which does not necessarily equate to the number of rows and columns. For 2D arrays though, the shape does correspond to rows and columns.