logo

NumPy - ndarray

Last Updated: 2024-02-13
  • fixed size at creation. Changing the size of an ndarray will create a new array and delete the original.
  • the elements are of the same data type

n-dimentional array

>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> arr = np.array(a)
>>> arr
array([1, 2, 3, 4])
>>> type(np.array(a))
<class 'numpy.ndarray'>

Check data type

>>> arr.dtype
dtype('int64')

Change the data type

>>> arr.astype(float)
array([ 1.,  2.,  3.,  4.])
>>> arr.astype(float).dtype
dtype('float64')

Get sizes

>>> arr.shape
(4,)

python array vs numpy array

python:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

numpy:

>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

ndarray operations

npa  = np.arange(10)

npa.std()
npa.mean()
npa.argmin() #return position of the min value
npa.argmax()
npa ** 2

linspace: (start, end, num)

np.linspace(0, 10, 11) array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

filter

npa[npa %2 == 0]

more efficient than list comprehension

(npa > 15) | (npa < 5)

exception: npa > 15 or npa < 5

boolean selection

>>> import numpy as np
>>> b = np.array([True, True, False, True])

>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])

>>> a[b]
array([0, 1, 3])

Ravel(Flatten)

>>> np.zeros([2,3,4])
array([[[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]],

       [[ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.]]])
>>> np.zeros([2,3,4]).ravel()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> np.zeros([2,3,4]).flatten()
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

ravel() will create another view, instead of modifying the original array.