Chapter 6 – NumPy (Detailed Notes)
NumPy is a Python library used for fast numerical computing. It provides arrays,
mathematical functions,
and tools for working with large data efficiently.
---------------------------------------
6.1 SHAPE
---------------------------------------
• The shape of an array tells its structure: number of rows, columns, and dimensions.
• 1D array example:
a = [Link]([2, 3, 8]) → shape = (3,)
• 2D array example:
b = [Link]([
[2, 3, 8],
[4, 5, 6]
]) → shape = (2, 3)
Meaning: 2 rows, 3 columns.
---------------------------------------
6.2 SLICING
---------------------------------------
• Slicing extracts specific parts of arrays.
• 1D slicing:
a[2] → 8
a[1:] → [3, 8]
• 2D slicing:
b[1] → second row → [4, 5, 6]
b[1, 2] → element 6
b[:, 1] → second column → [3, 5]
":" means select all values in that dimension.
---------------------------------------
6.3 MASKING
---------------------------------------
• Masking lets you filter or change values based on conditions.
Example:
a = [230, 10, 284, 39, 76]
mask = a > 200 → [True, False, True, False, False]
a[a > 200] = 0 → Values above 200 become 0
Advantages:
✔ No loops needed
✔ Very fast and short code
---------------------------------------
6.4 BROADCASTING
---------------------------------------
• Broadcasting allows arrays of different shapes to interact.
Example:
a = [[0,1],
[2,3],
[4,5]]
b = [10,100]
NumPy stretches b to match a's shape.
Broadcasting Rules:
1. Only dimensions of size 1 can stretch.
2. Comparison begins from last dimension backwards.
Broadcasting Error:
c shape = (2,3)
b shape = (2,)
c * b → ERROR: shape mismatch
Fix using None:
b[:, None] → shape becomes (2,1)
c * b[:, None] → works
---------------------------------------
6.5 dtype
---------------------------------------
• dtype defines the data type of array elements.
Common dtypes:
- int8 → -128 to 127
- uint8 → 0 to 255
- int64 → very large integers
- float → decimals
Example of overflow:
a = [Link]([200], dtype='uint8')
a + a → 144 (because 400 exceeds 255)
Fix:
[Link]('uint16') → supports larger numbers.
---------------------------------------
6.6 CHANGING dtype
---------------------------------------
• To convert an array to a new data type:
[Link]('uint64')
---------------------------------------
6.7 ADVANCED USAGE
---------------------------------------
NumPy provides:
• Advanced slicing
• Advanced indexing
• Vectorised operations
• Broadcasting rules
• Mathematical functions such as dot, cross, outer, etc.
---------------------------------------
6.8 EXERCISES SUMMARY
---------------------------------------
1. Create uint8 array and keep adding values until overflow.
2. Use masking to:
• multiply values <100 by 2 repeatedly
• select values between 150 and 200