Numpy Part -2

Numpy Part -2

Numpy array vs Python list

  1. As NumPy array are c based it is faster than the python's list

Indexing in Numpy array

  1. When there is no pattern and we cant use slicing, then we should go for fancy indexing

     import numpy as np
     my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
     x=np.array(my_list)
     x[:,[0,2]]
    
     #array([[1, 3],
           # [4, 6],
            #[7, 9]])
    
  2. Boolean Indexing (very important)

    • We create a boolean mask and where ever the mask is true only those numbers will be present in the array
```python
import numpy as np
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


x=np.array(my_list)
print(x>3)
print(x[x>3])

## [[False False False]
## [ True  True  True]
## [ True  True  True]]
## [4 5 6 7 8 9]
```

Broadcasting Numpy Arrays

  1. The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.

  2. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python.

  3. It does this without making needless copies of data and usually leads to efficient algorithm implementations.

  4. Always the SMALLER ARRAY IS BROADCASTED across the larger array

  5. It is done implicitly by numpy

  6. Rules for broadcasting are

    • Make the two arrays have the same number of dimensions.

      • If the numbers of dimensions of the two arrays are different, add new dimensions with size 1 to the head of the array with the smaller dimension.
    • Make each dimension of the two arrays the same size.

      • If the sizes of each dimension of the two arrays do not match, dimensions with size 1 are stretched to the size of the other array.

      • If there is a dimension whose size is not 1 in either of the two arrays, it cannot be broadcasted, and an error is raised.

example:

a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 2.0, 2.0])
a * b
## array([2.,  4.,  6.])