12.3.10.2.6. 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([[0.00000000e+000, 0.00000000e+000, 2.12199579e-314,
        2.12199579e-314, 4.24399158e-314, 4.24399158e-314,
        6.36598737e-314, 6.36598737e-314, 8.48798317e-314,
        8.48798317e-314],
       [2.12199579e-314, 6.36598737e-314, 2.12199579e-314,
        6.36598737e-314, 2.12199579e-314, 6.36598737e-314,
        2.12199579e-314, 6.36598737e-314, 2.12199579e-314,
        6.36598737e-314]])

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.092 seconds)