NumPy is the fundamental package for scientific computing with Python. It contains among other things:
The NumPy array object is the common interface for working with typed arrays of data across a wide-variety of scientific Python packages. NumPy also features a C-API, which enables interfacing existing Fortran/C/C++ libraries with Python and NumPy.
In [1]:
import numpy as np # standard import abbreviation
In [2]:
a = np.array([1, 2, 3]) # a NumPy array of three integers
a
Out[2]:
In [3]:
a.shape # tuple representing the size of each dimension
Out[3]:
In [4]:
a.ndim # number of dimensions
Out[4]:
In [5]:
a.dtype # Data type information
Out[5]:
In [6]:
b = np.array([1., 2., 3., 4.]) # a NumPy array of four floats
In [7]:
b.shape
Out[7]:
In [8]:
b.dtype
Out[8]:
NumPy provides various functions for creating common arrays
In [9]:
a = np.arange(10) # a range of values from (0) to 10
print(a)
In [10]:
a = np.arange(1, 10, 2, dtype='float32')
print(a)
print(a.dtype)
In [11]:
a = np.linspace(0, 10, 5) # 5 linearly spaced entries from 0 to 10
print(a)
In [12]:
a = np.array([1, 2, 3])
b = np.array([6, 7, 8])
In [13]:
a + b
Out[13]:
In [14]:
a * b
Out[14]:
But could that be done with lists? Yes but the syntax is not as nice.
In [15]:
a = [1, 2, 3]
b = [6, 7, 8]
In [16]:
c = [i+j for i, j in zip(a, b)]
print(c)
NumPy provides many mathematical functions which operate on arrays.
In [17]:
a = np.linspace(-np.pi, np.pi, 10)
In [18]:
np.sin(a)
Out[18]:
In [19]:
np.cos(a)
Out[19]:
In [20]:
a = np.arange(12).reshape(3, 4) # create a 2 dimensional array with dimensions of 3 and 4
print(a)
In [21]:
a.ndim
Out[21]:
In [22]:
a.shape
Out[22]:
In [23]:
2 * a
Out[23]:
In [24]:
a = np.arange(10)
In [25]:
a[3]
Out[25]:
In [26]:
a[2:-2]
Out[26]:
In [27]:
a[1::2]
Out[27]:
Multidimentional arrays can also be sliced. A comma seperates the dimensions.
In [28]:
b = np.arange(12).reshape(3, 4)
print(b)
In [29]:
b[1, 2]
Out[29]:
In [30]:
b[2] # select the entire second dimension
Out[30]:
In [31]:
b[1:3, :3] # slices are also allowed
Out[31]:
In [32]:
b[:, 2] # all elements in the first dimension
Out[32]:
In [33]:
# ... (ellipsis) will replace one or more dimensions
b[..., 2]
Out[33]:
In [34]:
a = np.arange(5)
In [35]:
selection = np.array([True, False, False, True, True])
a[selection]
Out[35]:
In [36]:
a[a>2]
Out[36]:
In [37]:
a = np.ma.arange(12).reshape(3, 4)
print(a)
In [38]:
a[2,2] = np.ma.masked
print(a)
In [39]:
b = a * 2
print(b)
In [40]:
# logical masking
a[a > 6] = np.ma.masked
print(a)
In [41]:
# unmasked an element
a[-1, -1] = 42
print(a)