Lesson 11 - NumPy arrays and operations

  • What is NumPy

    NumPy (short for Numerical Python) provides an efficient interface to store and operate on dense data buffers.
    It is similar to Python’s built-in list type, but NumPy arrays provide much more efficient storage and data operations as the arrays grow larger in size.

    NumPy is used to work with arrays. The array object in NumPy is called ndarray


    Creating NumPy array

    Let’s create one dimensional array of NumPy
    import numpy as np
    y = np.array([1, 2, 3, 4, 5, 6])
     
    NumPy array attributes
     
    ndim, shape, size are attributes of the array
    print(“y ndim: “, y.ndim)
    print(“y shape:”, y.shape)
    print(“y size: “, y.size)

    y ndim: 1
    y shape: (6,)
    y size: 6
     
     
     

     

    Array Indexing

    In a one-dimensional array, you can access the nth value (counting from zero) by specifying the desired index in square brackets

    Example:

    The index starts from 0, so the first element of the array is accessed using y[0]
    y[3]  outputs 4

    To index from the end of the array, you can use negative indices

    y[-2] outputs outputs 5

    Array Slicing

    The NumPy slicing syntax follows that of the standard Python list;

    To access a slice of an array y, use this:
    y[start:stop:step]

    import numpy as np
    y = np.array([0,1, 2, 3, 4, 5, 6,7,8,9,10])
    y[:5] # first five elements
    y[5:] # elements after index 5

    Array Concatenation

    Concatenation, or joining of two arrays in NumPy, is primarily accomplished through the routines np.concatenate.
    np.concatenate takes a tuple or list of arrays as its first argument.

    Example
    x = np.array([1, 2, 3, 4])
    y = np.array([4, 3, 2, 1])
    np.concatenate([x, y])

    array([1, 2, 3, 4, 4, 3, 2, 1])

    Splitting of arrays

    The opposite of concatenation is splitting, which is implemented by the function np.split

    we can pass a list of indices giving the split points:

    Example

    y = [1, 2, 3, 55, 55, 3, 2, 1]
    y1, y2, y3 = np.split(y, [3, 5])  # The array is to be split starting index 3 until index 5
    print(y1, y2, y3)
    [1 2 3] [55 55] [3 2 1]

     

    NumPy uFunctions

    NumPy has a few universal functions, which are useful in various computations.

     

    Suming the values

    import numpy as np
    y = np.array([1, 2, 3, 4, 5, 6])
    np.sum(y)
    21

    Min , Max and Mean

    np.min(y)
    1

    np.max(y)

    6
    np.mean(y)
    3.5
     
    Variance 
    np.var(y)
    2.9166666666666665
     
    Standard deviation
    np.std(y)
    1.707825127659933