Py Cheatsheet
Py Cheatsheet
## 1. Matrix Creation
```python
import numpy as np
3. Array Operations
# Where/nonzero
np.where(arr > 5, arr, -1) # Replace values <5 with -1
indices = np.nonzero(arr) # Get indices of non-zero elements
bigger_than_7_indices = np.nonzero(arr > 7) # Get indices of elements >7
# Unique elements
np.unique(arr, return_counts=True) # Values and counts
# Array sizing
arr.shape # Tuple of dimension sizes (number of elements per dim)
arr.size # Total elements (prod(shape))
arr.ndim # Number of dimensions
4. Reshaping
arr.reshape(5, 5) # Reshape `arr` to 5x5. Returns view if possible
arr.flatten() # Flatten array. Always returns copy
arr.ravel() # Flatten array. Returns view if possible
np.expand_dims(arr, 0) # Add new dimension at axis 0
np.squeeze(arr) # Remove singleton dimensions (dim of size 1)
1
5. Padding
np.pad(arr, 1) # Default 0-padding
np.pad(arr, (1,2), mode='edge') # Replicate edge values
np.pad(arr, 2, mode='constant', constant_values=5) # Pad with 5s
6. Aggregation
arr.sum(axis=0) # Column sums
arr.mean(axis=1) # Row averages
np.min(arr, axis=(0,1)) # Min across both dimensions
np.max(arr, axis=1) # Max over rows (across columns: dim 1)
7. Iteration
# 1D
for val in arr.flat: print(val)
# 2D with indices
for idx, val in np.ndenumerate(arr):
print(f"Index {idx}: {val}")
# 2D without indices
for row in arr:
for val in row:
print(val)
Type Checking
s.isalpha() # True if all alphabetic
s.isdigit() # True if all digits
s.isalnum() # Alpha-numeric check
2
s.startswith("Hello") # True
lst.index(2) # Returns 1
lst.append(4) # [1,2,3,4]
lst.extend([5,6]) # [1,2,3,4,5,6]
lst.insert(0, 0) # Insert at position 0
lst[::-1] # Reverse list
[x*2 for x in lst] # List comprehension
Common Pitfalls
Python Basics
1. Mutable Default Arguments
2. Shallow Copying
a = [[1,2], [3,4]]
b = a.copy() # Outer list copied, inner lists referenced
# use deep copy:
import copy
b = copy.deepcopy(a)
3. Integer Division
Numpy Gotchas
1. View vs Copy
3
a = np.arange(10)
b = a[::2] # View (modifying b affects a)
c = a[::2].copy() # Independent copy
2. Boolean Indexing
3. Broadcasting Errors
a = np.ones((3,4))
b = np.ones((4,3))
a + b # Error! Use a + b.T
4. In-Place Operations
a = np.array([1,2,3], dtype=np.int8)
a += 100 # Overflow! (Becomes [101, 102, 103] % 256)
5. Axis Confusion
7. Empty Slices
arr = np.array([])
arr.mean() # Returns nan! Check size first
9. Order of Operations
a = np.array([1,2,3])
b = a * 2 + 1 # Equivalent to (a * 2) + 1