numpy arrays examples

In [1]:
import numpy as np

Create N dimensional arrays:

By literal - note that the number of opening squares equals the dimension

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

Create array filled with random values: np.empty of type np.int8

In [3]:
b = np.empty( (3,2), dtype=np.int8  )
b
Out[3]:
array([[-120,  123],
       [  -2,   89],
       [   7,  127]], dtype=int8)

Create array by np.arange() method (quite simmilar to python's range())

In [4]:
b = np.arange(0,21,2)
b
Out[4]:
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20])

Simple indexing

In [5]:
a[1][2]
Out[5]:
6

Basic numpy properties and methods

The number of axes (dimensions) of the array: a.ndim

In [6]:
a = np.array([[1,2,3],[4,5,6]])
a.ndim
Out[6]:
2

Tuple of integers indicating the size of the array in each dimension: ndarray.shape

In [7]:
a = np.array([[1,2,3],[4,5,6]])
a.shape
Out[7]:
(2, 3)
In [8]:
b = np.array([[1,2],[3,4],[5,6]])
b.shape
Out[8]:
(3, 2)

Total number of elements of the array: a.size

In [9]:
a = np.array([[1,2,3],[4,5,6]])
a.size
Out[9]:
6

The size in bytes of each element of the array: a.itemsize

In [10]:
a = np.array([[1,2,3],[4,5,6]])
a.itemsize
Out[10]:
8

Array Manipulations

Flatten the array
In [11]:
a = np.array([[1,2,3],[4,5,6]])
a.ravel()
Out[11]:
array([1, 2, 3, 4, 5, 6])

reshaping arrays: np.reshape()

In [12]:
a = np.array([[1,2,3],[4,5,6]])
a.shape
Out[12]:
(2, 3)
In [13]:
a.reshape(3,2)
Out[13]:
array([[1, 2],
       [3, 4],
       [5, 6]])
In [14]:
a.reshape(1,6)
Out[14]:
array([[1, 2, 3, 4, 5, 6]])

Arrays Algebra (Element Wise)

In [15]:
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2,3],[4,5,6]])

a+b
Out[15]:
array([[ 2,  4,  6],
       [ 8, 10, 12]])

matrix product: dot()

In [16]:
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2],[3,4],[5,6]])

a.dot(b)
Out[16]:
array([[22, 28],
       [49, 64]])
In [17]:
b.dot(a)
Out[17]:
array([[ 9, 12, 15],
       [19, 26, 33],
       [29, 40, 51]])