Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Data Analytics Using Python/1 NumPy.ipynb
3074 views
Kernel: Python 3 (ipykernel)

Numerical Analysis using Python

What is NumPy?

NumPy (Numerical Python) is a Python library for numerical computing. It provides:

  • Efficient array operations

  • Mathematical and logical operations

  • Linear algebra, Fourier transform, and more.

Let's start by importing NumPy.

a=[1,2,3] b=[20,30,10] import numpy as np a1=np.array(a) b1=np.array(b) a1+b1 a1*b1 a1**2
array([1, 4, 9])
import numpy as np print(np.__version__)
1.23.5

1. Array Creation

NumPy arrays are more efficient than Python lists for numerical computations.

# Creating arrays arr = np.array([1, 2, 3]) print('Array:', arr) print('Type:', type(arr))
Array: [1 2 3] Type: <class 'numpy.ndarray'>
## Different ways of creating arrays zeros = np.zeros((2, 3),dtype=int) zeros
array([[0, 0, 0], [0, 0, 0]])
o = np.ones((3, 3)) o
array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
z=np.ones((3,2,2),dtype=int) z
array([[[1, 1], [1, 1]], [[1, 1], [1, 1]], [[1, 1], [1, 1]]])
a2 = np.arange(20, 8, -2) a2 a3=a2.reshape((2,3)) a3
array([[20, 18, 16], [14, 12, 10]])
z=np.full((3),fill_value=(5,10,15),dtype=int) z
array([ 5, 10, 15])
z=np.full((3,3),fill_value=(1,2,3),dtype=int) z
array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

Quick Practice:

  • Create an array using arange function starting with 50 and end with 10.

  • reshape it to 2D array

linspace = np.linspace(0, 1, 3) linspace
array([0. , 0.5, 1. ])

Different Dimensions

# 1D Array array_1d = np.array([1, 2, 3, 4, 5]) print("1D Array:") print(array_1d) print("Shape:", array_1d.shape) print()
1D Array: [1 2 3 4 5] Shape: (5,)
# 2D Array a_2 = np.array([[1, 2, 3], [4, 5, 6]]) print("2D Array:") print(a_2) print("Shape:", a_2.shape) print()
2D Array: [[1 2 3] [4 5 6]] Shape: (2, 3)
# 3D Array array_3d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) print("3D Array:") print(array_3d) print("Shape:", array_3d.shape)
3D Array: [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] Shape: (2, 2, 3)

Quick Practice:

  1. Create a 4x4 matrix of all fives.

  2. Create an array of 20 numbers between 10 and 50 (inclusive).

2. Array Attributes

a = np.array([[1,2,3],[4,5,6]]) print('Shape:', a.shape) print('Size:', a.size) print('Data Type:', a.dtype) print('Dimension:', a.ndim)
Shape: (2, 3) Size: 6 Data Type: int32 Dimension: 2

3. Indexing and Slicing

array_1d
array([1, 2, 3, 4, 5])
array_1d[1:3] array_1d[1]
2
a_2
array([[1, 2, 3], [4, 5, 6]])
a_2[1,1]
5
array_3d
array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]])
array_3d[0,0,2]
3
array_3d[1,1:3,1:3]
array([[11, 12]])
array_3d[1,:,1]
array([ 8, 11])

Quick Practice:

  1. Extract every 2nd element from an array of numbers 0-20.

  2. From a 3x3 matrix, extract the last column.

4. Array Operations (Element-wise)

x = np.array([1,2,3]) y = np.array([4,5,6]) print('Addition:', x + y) print('Multiplication:', x * y) print('Dot Product:', np.dot(x, y))
Addition: [5 7 9] Multiplication: [ 4 10 18] Dot Product: 32

5. Universal Functions (ufuncs)

arr = np.array([1,4,9,16]) print('Square root:', np.sqrt(arr)) print('Exponential:', np.exp(arr)) print('Sine:', np.sin(arr))

6. Reshape and Transpose

a = np.arange(12) reshaped = a.reshape(3,4) print('Reshaped:', reshaped) print('Transpose:', reshaped.T) reshaped.T
Reshaped: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Transpose: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]])

7. Stacking and Splitting

a = np.array([[1,2],[3,4]]) b = np.array([[5,6],[7,8]]) a
array([[1, 2], [3, 4]])
v_p= np.vstack((a,b)) type(v_p) print(a.shape) v_p.shape v_p
(2, 2)
array([[1, 2], [3, 4], [5, 6], [7, 8]])
h_p = np.hstack((a,b)) h_p.shape h_p
array([[1, 2, 5, 6], [3, 4, 7, 8]])

8. Broadcasting

Computation between array of differrent shapes

  • smaller array should always of 1*n shape , where n = number of colums in higher order array

a=np.array([1,2,0]) # 1*3 a
array([1, 2, 0])
b=np.array([[2,2,2],[1,1,1],[3,3,3]]) # 3*3 b
array([[2, 2, 2], [1, 1, 1], [3, 3, 3]])
d=a+b

9. Random Module

r = np.random.rand(3,3) r
array([[0.59986582, 0.44095902, 0.15436578], [0.59329516, 0.71232562, 0.70069948], [0.73242941, 0.11822785, 0.70461349]])
r_int = np.random.randint(0,100,(2,2)) r_int
array([[90, 20], [37, 39]])
### Use seed to fix random generated values np.random.seed(0) r = np.random.rand(3,3) r
array([[0.5488135 , 0.71518937, 0.60276338], [0.54488318, 0.4236548 , 0.64589411], [0.43758721, 0.891773 , 0.96366276]])
## Use seed to fix random generated values np.random.seed(2) r_int = np.random.randint(0,10) r_int
8

10. Linear Algebra

matrix = np.array([[1,2],[3,4]]) print('Determinant:', np.linalg.det(matrix)) print('Inverse:', np.linalg.inv(matrix)) print('Eigenvalues:', np.linalg.eig(matrix)[0])
Determinant: -2.0000000000000004 Inverse: [[-2. 1. ] [ 1.5 -0.5]] Eigenvalues: [-0.37228132 5.37228132]

11. Advanced Functions

# Where condition arr = np.array([10,20,30,40,50]) print(np.where(arr>25, 'Yes', 'No'))
['No' 'No' 'Yes' 'Yes' 'Yes']
# Unique and Sorting vals = np.array([1,2,2,3,3,3,4,-9,80,65,65,]) print('Unique:', np.unique(vals))
Unique: [-9 1 2 3 4 65 80]
np.sort(vals)
array([-9, 1, 2, 2, 3, 3, 3, 4, 65, 65, 80])