12.3.10.2.3. Create array#

This demo shows the features of numpy (https://numpy.org/doc/stable/user/quickstart.html).

import numpy as np
import matplotlib.pyplot as plt


array = np.arange(15).reshape(3, 5)
array.shape
(3, 5)
array.ndim
2
array.dtype.name
'int32'
array.itemsize
4
array.size
15
type(array)

dtype, dimensions

array2 = np.array([1.2, 3.5, 5.1])
array2.dtype.name
'float64'
np.array([(1.5, 2, 3), (4, 5, 6)])
array([[1.5, 2. , 3. ],
       [4. , 5. , 6. ]])
np.array([[1, 2], [3, 4]], dtype=complex)
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j]])

Zeros, ones, empty

np.zeros((3, 4))
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
np.ones((2, 3, 4), dtype=np.int16)
array([[[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]],

       [[1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 1, 1]]], dtype=int16)
np.empty((2, 10))
array([[-2.3107758 , -2.47187343, -2.47187343, -2.63261058, -2.63261058,
        -2.79310345, -2.79310345, -2.95344595, -2.95344595, -3.        ],
       [-2.22936756, -2.34787573, -2.34787573, -2.46687606, -2.46687606,
        -2.5862069 , -2.5862069 , -2.70573978, -2.70573978, -2.74047929]])

Sequence of numbers

np.arange(10, 30, 5)
np.arange(0, 2, 0.3)
array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
np.linspace(0, 2, 9)
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  ])
x = np.linspace(0, 2 * np.pi, 100)
f = np.sin(x)

plt.figure()
plt.plot(f)
plt.show()
demo create

Reshape

np.arange(12).reshape(4, 3)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
c = np.arange(24).reshape(2, 3, 4)

Total running time of the script: (0 minutes 0.063 seconds)