Creating NumPy arrays

The NumPy multidimensional array object is called ndarray.

NumPy arrays are typed arrays of a fixed size. NumPy arrays are homogeneous which means they can contain objects of only one type (unlike the Python lists which are heterogeneous and can contain items of different types).

An ndarray is made of two parts:

  • The data of the array – stored in a contiguous block of memory
  • The metadata – which describes the data

NumPy arrays can execute vectorized operations processing a complete array (Python lists use loops and execute operations on each item of the list).

NumPy lists are indexed from 0 (like Python lists).

Creating a NumPy array

import numpy as np
a = np.arange(5)

The data type of the array is int64 since I am using 64 bit Python.

a.dtype

#out
dtype('int64')

This creates a NumPy array in the interval (0, 5). The 0 is included but 5 is not included.

a

#out
array([0, 1, 2, 3, 4])

The shape property of a NumPy array is a tuple. In our case is a tuple with one element (5,) which represent the length of each dimension of the array.

a.shape

#out
(5,)

Creating a NumPy multidimensional array

The creation of a multidimensional array is demonstrated below:

import numpy as np

a = np.array([np.arange(2), np.arange(2)])
a

#out
array([[0, 1],
       [0, 1]])

In this situation the shape will be:

a.shape

#out
(2, 2)

You may modify this example and change the range of the arrays or even add more arrays.

import numpy as np

a = np.array([np.arange(3), np.arange(3), np.arange(3), np.arange(3)])
a

#out
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2],
       [0, 1, 2]])

In this situation the shape will be:

a.shape

#out
(4, 3)

Leave a Reply