The Dimension of a Numpy Array

Numpy is a popular Python library for data science focusing on arrays, vectors, and matrices. If you work with data, you simply cannot avoid NumPy.

Challenge: How to get the number of dimensions of a NumPy array?

Solution: Use the attribute array.ndim to access the number of dimensions of a NumPy array. Note that this an attribute, not a function.

The one-dimensional array has one dimension:

import numpy as np

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

The two-dimensional array has two dimensions:

import numpy as np

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

And the three-dimensional array has three dimensions:

import numpy as np

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

Background: Before we move on, you may ask: What is the definition of dimensions in an array anyways?

Numpy does not simply store a bunch of data values in a loose fashion (you can use lists for that). Instead, NumPy imposes a strict ordering to the data – it creates fixed-sized axes.

Don’t confuse an axis with a dimension. A point in 3D space, e.g. [1, 2, 3] has three dimensions but only a single axis. You can think of an axis as the depth of your nested data. If you want to know the number of axes in NumPy, count the number of opening brackets '[' until you reach the first numerical value.

Related Article: NumPy Shape

NumPy Puzzle Dimensionality

Can you solve the following NumPy puzzle that tests what you’ve learned so far?

import numpy as np

# salary in ($1000) [2015, 2016, 2017]
dataScientist = [133, 132, 137]
productManager = [127, 140, 145]
designer = [118, 118, 127]
softwareEngineer = [129, 131, 137]

a = np.array([dataScientist,

Exercise: What is the output of this puzzle?

You can solve it in our interactive puzzle app

Puzzle Dim NumPy

In this puzzle, we use data about the salary of four jobs: data scientists, product managers, designers, and software engineers. We create four lists that store the yearly average salary of the four jobs in thousand dollars for three years 2015, 2016, and 2017.

Then, we merge these four lists into a two-dimensional array (denoted as matrix). You can think about a two-dimensional matrix as a list of lists. A three-dimensional matrix would be a list of lists of lists. You get the idea.

In the puzzle, each salary list of a single job becomes a row of a two-dimensional matrix. Each row has three columns, one for each year. The puzzle prints the dimension of this matrix. As our matrix is two-dimensional, the solution of this puzzle is 2.

Related NumPy Video

Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy

Leave a Comment

Your email address will not be published. Required fields are marked *