Numerical Python (NumPy Basics)

Data ScienceNumPyFree Lesson

Advertisement

Introduction

NumPy provides efficient array computing with vectorization. It enables fast numerical operations without Python loops, leveraging optimized C code.

Array Creation

import numpy as np

# From Python list
arr = np.array([1, 2, 3, 4, 5])
print(arr)

# Zeros and ones
zeros = np.zeros(10)
ones = np.ones((3, 3))

# Range
range_arr = np.arange(0, 10, 2)  # [0, 2, 4, 6, 8]

# Linespace
points = np.linspace(0, 1, 5)  # [0, 0.25, 0.5, 0.75, 1]

Vectorized Operations

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Element-wise operations
arr + 1      # [2, 3, 4, 5, 6]
arr * 2      # [2, 4, 6, 8, 10]
arr ** 2     # [1, 4, 9, 16, 25]
np.sqrt(arr) # [1, 1.41, 1.73, 2, 2.23]

# Array operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
a + b        # [5, 7, 9]
a * b        # [4, 10, 18]

Broadcasting

import numpy as np

# Different shapes broadcast
a = np.array([[1], [2], [3]])  # 3x1
b = np.array([10, 20, 30])     # 3
result = a + b  # 3x3

print(result)
# [[11, 21, 31],
#  [12, 22, 32],
#  [13, 23, 33]]

Array Indexing

import numpy as np

arr = np.arange(12).reshape(3, 4)

print(arr[0, 0])        # First element
print(arr[1, :])        # Second row
print(arr[:, 2])        # Third column
print(arr[1:3, 1:3])    # Submatrix

# Boolean indexing
arr[arr > 5]  # Elements > 5

Array Functions

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

# Statistical functions
np.sum(arr)
np.mean(arr)
np.std(arr)
np.min(arr)
np.max(arr)
np.argmin(arr)  # Index of min
np.argmax(arr)  # Index of max

# Array methods
arr.sum()
arr.mean()
arr.std()
arr.min()
arr.max()

Practice Problems

  1. Create arrays using different methods
  2. Perform vectorized operations
  3. Use broadcasting for operations
  4. Index arrays with slices
  5. Apply statistical functions

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement