Skip to content
Home » numpy Part 3 – numpy Array Dimensions

numpy Part 3 – numpy Array Dimensions

Spread the love

Today we’ll be talking about numpy array dimensions.

numpy array dimensions

Vectors – 1-Dimensional Arrays

In numpy we can create multidimensional arrays. The arrays we’ve been creating so far are all 1-dimensional. You can check out numpy array dimensions using the ndim method:

>>> a = np.array([1, 2, 3])
>>> print(a)
[1 2 3]
>>> np.ndim(a)
1

1- dimensional arrays are called vectors. They contain all elements of the same type. You can check the type of the elements of an array using the dtype attribute:

>>> print(a.dtype)
int32

Scalars – 0-Dimensional Arrays

If we use scalars, which are just integer or float values, numpy treats them as 0-dimensional arrays. Have a look:

>>> b = np.array(5)
>>> c = np.array(3.8)
>>> print(b)
5
>>> print(c)
3.8
>>> np.ndim(b)
0
>>> np.ndim(c)
0

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Multidimensional Arrays

We can also create arrays of more than 1 dimension. This can be done by passing nested lists or tuples to the array method. There is theoretically no limit as to the maximum number of numpy array dimensions, but you should keep it reasonably low or otherwise you will soon lose track of what’s going on or at least you will be unable to handle such complex arrays anymore.

Here’s an example of a 2-dimensional array:

>>> a = [[1, 2, 3], [5, 6, 7], [8, 9, 10]]
>>> A = np.array(a)
>>> print(A)
[[ 1  2  3]
 [ 5  6  7]
 [ 8  9 10]]
>>> A.ndim
2

And here’s an example of a 3-dimensional array:

>>> b = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
>>> B = np.array(b)
>>> print(B)
[[[ 1  2]
  [ 3  4]]

 [[ 5  6]
  [ 7  8]]

 [[ 9 10]
  [11 12]]]
>>> B.ndim
3

By the way, instead of using the ndim method of numpy, we can use the ndim attribute directly on the numpy array:

>>> np.ndim(B)
3
>>> B.ndim
3

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here you can watch the video version:


Spread the love

Leave a Reply