Learn data science and machine learning by building real-world projects on Jovian
In [ ]:
! pip install jovian
import jovian
In [3]:
import numpy as np

Why to use NumPy

In [102]:
# array size is very large
array = np.random.rand(1000000)
%timeit sum(array)
print('\n')
%timeit np.sum(array)
362 ms ± 6.77 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 1.9 ms ± 37.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Introduction to Ufuncs

Arithematic Functions

In [56]:
# The standard addition, subtraction, multiplication, and division 
x = np.arange(4)
print("x     =", x)
print("x + 5 =", x + 5)
print("x - 5 =", x - 5)
print("x * 2 =", x * 2)
print("x / 2 =", x / 2)
print("x // 2 =", x // 2)  # floor division
print("-x     = ", -x)
print("x ** 2 = ", x ** 2)
print("x % 2  = ", x % 2)
x = [0 1 2 3] x + 5 = [5 6 7 8] x - 5 = [-5 -4 -3 -2] x * 2 = [0 2 4 6] x / 2 = [0. 0.5 1. 1.5] x // 2 = [0 0 1 1] -x = [ 0 -1 -2 -3] x ** 2 = [0 1 4 9] x % 2 = [0 1 0 1]
In [68]:
# Built-in NumPy wrappers for arithmetic operations
a = np.arange(3)
b = np.array([10,10,10]) 

print("Add two  arrays",np.add(a,b))
print('Subtract two arrays:',np.subtract(a,b))
print('Multiply the two arrays:',np.multiply(a,b)) # Matrix Multiplication
print('Divide the two arrays:',np.divide(a,b))
Add two arrays [10 11 12] Subtract two arrays: [-10 -9 -8] Multiply the two arrays: [ 0 10 20] Divide the two arrays: [0. 0.1 0.2]

Trigonometric and Inverse Trigonometric Functions

In [69]:
# Trigonometric functions
theta = np.linspace(0, np.pi, 3)
# np.pi = 3.14159.. -> 180degrees
# np.linespace creates n equal partitions in range of (start,end)
print("theta      = ", theta)
print("sin(theta) = ", np.sin(theta))
print("cos(theta) = ", np.cos(theta))
print("tan(theta) = ", np.tan(theta))
theta = [0. 1.57079633 3.14159265] sin(theta) = [0.0000000e+00 1.0000000e+00 1.2246468e-16] cos(theta) = [ 1.000000e+00 6.123234e-17 -1.000000e+00] tan(theta) = [ 0.00000000e+00 1.63312394e+16 -1.22464680e-16]
In [63]:
# Inverse Trigonometric Functions
x = [-1, 0, 1]
print("x         = ", x)
print("arcsin(x) = ", np.arcsin(x))
print("arccos(x) = ", np.arccos(x))
print("arctan(x) = ", np.arctan(x))
x = [-1, 0, 1] arcsin(x) = [-1.57079633 0. 1.57079633] arccos(x) = [3.14159265 1.57079633 0. ] arctan(x) = [-0.78539816 0. 0.78539816]

Exponents and logarithms

In [64]:
# Exponents and logarithms of NumPy arrays
x = [1, 2, 3]
print("x     =", x)
print("e^x   =", np.exp(x))
print("2^x   =", np.exp2(x))
print("3^x   =", np.power(3, x))
x = [1, 2, 3] e^x = [ 2.71828183 7.3890561 20.08553692] 2^x = [2. 4. 8.] 3^x = [ 3 9 27]
In [65]:
x = [1, 2, 4, 10]
print("x        =", x)
print("ln(x)    =", np.log(x))
print("log2(x)  =", np.log2(x))
print("log10(x) =", np.log10(x))
x = [1, 2, 4, 10] ln(x) = [0. 0.69314718 1.38629436 2.30258509] log2(x) = [0. 1. 2. 3.32192809] log10(x) = [0. 0.30103 0.60205999 1. ]

Advances Ufuncs

In [80]:
# reduce method
x = np.arange(1, 6)
print("Sum of all elements in array",np.add.reduce(x))
print("Product of all elements with-in array",np.multiply.reduce(x))

Sum of all elements in array 15 Product of all elements with-in array 120
In [83]:
# accumlate method
print("Intermediate result of sum of array",np.add.accumulate(x),'\n')
print("Intermediate result of product of array",np.multiply.accumulate(x),'\n')
Intermediate result of sum of array [ 1 3 6 10 15] Intermediate result of product of array [ 1 2 6 24 120]

Multi dimensional aggregates

In [123]:
# Multi dimensional Aggregates
M = np.random.random((3, 4))
print('N-dimensional array :\n',M)
print('Sum of all array elements:',M.sum())
print("Column-wise minimum number:\n",M.min(axis=0))
print("Row-wise minimum number:\n",M.min(axis=1))
print("Mean height:", M.mean())
print("Standard deviation:", M.std())
N-dimensional array : [[0.5131531 0.95053537 0.6109008 0.09932112] [0.36430393 0.91123806 0.83922517 0.78829697] [0.90088348 0.95180424 0.57403711 0.44449231]] Sum of all array elements: 7.9481916499481295 Column-wise minimum number: [0.36430393 0.91123806 0.57403711 0.09932112] Row-wise minimum number: [0.09932112 0.36430393 0.44449231] Mean height: 0.6623493041623442 Standard deviation: 0.2612193151159209

Broadcasting

Broadcasting
  • Another extremely useful feature of ufuncs is the ability to operate between arrays of different sizes and shapes, a set of operations known as broadcasting
In [128]:
# Broadcasting
a = np.arange(3)
b = np.arange(3)[:, np.newaxis]

print('a array:\n',a)
print('b array:\n',b)
print('a+b:\n',a+b)
a array: [0 1 2] b array: [[0] [1] [2]] a+b: [[0 1 2] [1 2 3] [2 3 4]]

Broadcasting 1

In [131]:
# Broadcasting example 1
M = np.ones((2, 3))
a = np.arange(3)
print('Addition after Broadcasting (M + a):',M+a)
Addition after Broadcasting (M + a): [[1. 2. 3.] [1. 2. 3.]]

Broadcasting 2

In [134]:
# Broadcasting example 2
a = np.arange(3).reshape((3, 1))
b = np.arange(3)
print('Addition after Broadcasting (a + b):\n',a+b)
Addition after Broadcasting (a + b): [[0 1 2] [1 2 3] [2 3 4]]

Broadcasting 3

In [136]:
# Broadcasting example 3
M = np.ones((3, 2))
a = np.arange(3)
print("(M + a) :\n",M+a)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-136-bd75651a5dab> in <module> 2 M = np.ones((3, 2)) 3 a = np.arange(3) ----> 4 print("(M + a) :\n",M+a) ValueError: operands could not be broadcast together with shapes (3,2) (3,)
In [137]:
jovian.commit()
[jovian] Attempting to save notebook.. [jovian] Uploading notebook.. [jovian] Capturing environment..
[jovian] Error: Anaconda binary not found. Please make sure the "conda" command is in your system PATH or the environment variable $CONDA_EXE points to the anaconda binary
[jovian] Committed successfully! https://jovian.ml/v-snehith999/numpy-basics-part-2
In [ ]:
jovian.commit(message="jovian version commit message",
              git_message="git commit message",environment='none' )
[jovian] Attempting to save notebook..
In [ ]:
 
In [ ]: