SwadhyAI Notes

All Python notes

NumPy Tutorial 🔢

Numerical Python

NumPy is the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays.

✨ Why NumPy?

  • Speed: NumPy arrays are up to 50x faster than Python lists.
  • Memory: NumPy arrays take up less memory.
  • Convenience: Makes complex mathematical operations easy.

📦 Creating Arrays

The main object in NumPy is the ndarray.

python
import numpy as np

# 1-D Array
arr1 = np.array([1, 2, 3, 4, 5])

# 2-D Array (Matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])

print(arr2.shape) # (2, 3) - 2 rows, 3 columns

🧮 Array Operations

You can perform element-wise operations easily.

python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Addition
print(a + b) # [5 7 9]

# Multiplication
print(a * 2) # [2 4 6]

# Dot Product
print(np.dot(a, b)) # 32

✨ Pro Tip: Slicing

NumPy slicing is powerful and similar to Python lists, but works on multiple dimensions.

python
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0, 1:4]) # [2 3 4] (Row 0, indices 1 to 3)