NumPyΒΆ

NumPy is a library for multidimensional array objects.

import numpy as np
x = np.array([1, 2, 3])
x
array([1, 2, 3])
2 * x
array([2, 4, 6])
np.shape(x)
(3,)
y = np.array([[4], [5], [6]])
y
array([[4],
       [5],
       [6]])
x + y
array([[5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
z = x * y
z
array([[ 4,  8, 12],
       [ 5, 10, 15],
       [ 6, 12, 18]])
np.shape(z)
(3, 3)
np.savez_compressed('nums.npz', x=x, y=y)
nums = np.load('nums.npz')
[key for key in nums.keys()]
['x', 'y']
nums['x']
array([1, 2, 3])
nums['x'] == x
array([ True,  True,  True])
np.linspace(0, 10, 11)
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.arange(0, 10, 0.5)
array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. ,
       6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])
x = np.arange(10)
y = np.arange(10)
xx, yy = np.meshgrid(x, y)
print(np.shape(xx))
xx
(10, 10)
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
np.add(x, y)
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
np.multiply(x, y)
array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])
np.mean(x)
4.5
np.nan
nan
np.nanmean([0, 1, 2, 3, np.nan])
1.5
np.reshape(x, (2, 5))
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
np.where(x < 5, x, x * 10)
array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

For more information, see the documentation.