NumPy is an Open Source package available for Python 2 and Python 3 that provides:
ndarray: a high-performance class to represent multidimensional arrays;
In [1]:
import numpy as np
a0 = np.array([1.1, 2.2, 3.3])
The np.array function creates instances of the ndarray class:
In [22]:
type(a0)
Out[22]:
All elements of an ndarray are of the same type, which you can inspect as the .dtype property:
In [3]:
a0.dtype
Out[3]:
In [24]:
a1 = np.array(range(10))
In [25]:
a1
Out[25]:
In [26]:
a1.dtype
Out[26]:
In [27]:
a1 = np.arange(10)
a1
Out[27]:
NumPy can pick a type automatically, or you can assign one explicitly:
In [34]:
ab = np.array([1, 2, 3], dtype=np.uint8)
ab
Out[34]:
A sequence of nested sequences with equal lenghts can be used to build a multidimensional array, like this 2D array:
In [11]:
a2 = np.array([[10, 20], [30, 40], [50, 60]])
a2
Out[11]:
In [19]:
at = a2.transpose()
at
Out[19]:
Many array operations return views which share the undelying data with the source array. That's the case of the T property and the .transpose() method:
In [20]:
at[0, 1] = 99
In [21]:
a2
Out[21]:
You can also use the np.zeros, np.ones and np.identity to build arrays filled with zeros and ones:
In [41]:
np.ones((3, 5))
Out[41]:
In [42]:
np.identity(4)
Out[42]:
The np.random module has functions to build arrays filled with random numbers using several distributions:
In [29]:
a3 = np.random.random((2, 3))
a3
Out[29]:
Many scalar operations are supported, and are vectorized:
In [30]:
a3 * 10
Out[30]:
In [47]:
a3 > .5
Out[47]:
Starting with Python 3.5, the @ operator does matrix multiplication (dot product):
In [32]:
a2 @ a3
Out[32]:
If you are using Python 3.4 or older, you must use the .dot() method for the dot product:
In [33]:
a2.dot(a3)
Out[33]:
In [ ]: