NumPy Basics and Arrays
Duration: 18 min
Visual: NumPy Array Structure
1D Array (Vector)
[1, 2, 3, 4, 5]
2D Array (Matrix)
[[1, 2, 3],
[4, 5, 6]]
3D Array (Tensor)
[[[1, 2], [3, 4]],
[[5, 6], [7, 8]]]Key Concepts Table
| Concept | Definition | Example |
|---|---|---|
| Array | N-dimensional collection | np.array([1,2,3]) |
| Shape | Dimensions | (3,4) for 3x4 matrix |
| Dtype | Data type | int32, float64 |
| Indexing | Access elements | arr[0] |
| Slicing | Get subset | arr[1:3] |
| Broadcasting | Operate on different shapes | arr + 5 |
| Vectorization | Efficient operations | np.sum(arr) |
What is NumPy?
NumPy is a Python library for numerical computing. It provides efficient arrays and mathematical functions to implement the math concepts you learned.
Creating Arrays
import numpy as np
# 1D array (vector)
a = np.array([1, 2, 3])
# 2D array (matrix)
A = np.array([[1, 2], [3, 4]])
# Array of zeros
zeros = np.zeros((2, 3))
# Array of ones
ones = np.ones((2, 3))
# Range of values
range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
# Random array
random_arr = np.random.rand(3, 3)Array Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise operations
print(a + b) # [5, 7, 9]
print(a * b) # [4, 10, 18]
print(a / b) # [0.25, 0.4, 0.5]
# Scalar operations
print(a * 2) # [2, 4, 6]
print(a + 10) # [11, 12, 13]Array Properties
A = np.array([[1, 2, 3], [4, 5, 6]])
print(A.shape) # (2, 3) - 2 rows, 3 columns
print(A.size) # 6 - total elements
print(A.dtype) # int64 - data type
print(A.ndim) # 2 - number of dimensionsIndexing and Slicing
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10 - first element
print(a[-1]) # 50 - last element
print(a[1:4]) # [20, 30, 40] - elements 1 to 3
print(a[::2]) # [10, 30, 50] - every 2nd element❓ What does np.array([1, 2, 3]).shape return?
Practice Quizzes
Quiz 1: What is the shape of a 3x4 matrix?
- [✓] (3,4)
- (4,3)
- 12
- 7
Quiz 2: What does broadcasting allow?
- Sending data
- [✓] Operating on different shapes
- Creating arrays
- Indexing arrays
Quiz 3: How do you create a NumPy array?
- np.create()
- [✓] np.array()
- np.make()
- np.new()