Creation of Numpy arrays

Creation of Numpy arrays#

Code using numpy usually starts with the import statement

import numpy as np

NumPy provides the type np.ndarray. Such array are multidimensionnal sequences of homogeneous elements. They can be created for example with the commands:

# from a list
l = [10.0, 12.5, 15.0, 17.5, 20.0]
np.array(l)
array([10. , 12.5, 15. , 17.5, 20. ])
# fast but the values can be anything
np.empty(4)
array([4.67886622e-310, 0.00000000e+000, 4.67947776e-310, 4.67947784e-310])
# slower than np.empty but the values are all 0.
np.zeros([2, 6])
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]])
# multidimensional array
a = np.ones([2, 3, 4])
print(a.shape, a.size, a.dtype)
a
(2, 3, 4) 24 float64
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.]]])
# like range but produce 1D numpy array
np.arange(4)
array([0, 1, 2, 3])
# np.arange can produce arrays of floats
np.arange(4.0)
array([0., 1., 2., 3.])
# another convenient function to generate 1D arrays
np.linspace(10, 20, 5)
array([10. , 12.5, 15. , 17.5, 20. ])

A NumPy array can be easily converted to a Python list.

a = np.linspace(10, 20, 5)
list(a)
[np.float64(10.0),
 np.float64(12.5),
 np.float64(15.0),
 np.float64(17.5),
 np.float64(20.0)]
# Or even better
a.tolist()
[10.0, 12.5, 15.0, 17.5, 20.0]