NumPy Exercises
N1. Create a 3×3 array of numbers 1–9.
N1. Create a 3×3 array of numbers 1–9.
np.arange(1,10).reshape(3,3)
N2. Create a 4×4 identity matrix. np.eye(4)
N3. Make a 1-D array of 10 zeros with the 5th element = 1.
a=np.zeros(10); a[4]=1
N4. Reverse a 1-D array. a[::-1]
N5. Create a 5×5 checkerboard of 0s and 1s.
b=np.zeros((5,5),int); b[1::2,::2]=1; b[::2,1::2]=1
N6. Normalize a random 3×3 matrix to [0,1].
(m-m.min())/(m.max()-m.min())
N7. Multiply a 5×3 by a 3×2 matrix. A @ B
N8. Negate all elements between 3 and 8 in place.
a[(a>=3)&(a<=8)] *= -1
N9. Find common values between two arrays. np.intersect1d(a,b)
N10. Get the positions where two arrays match. np.where(a==b)
N11. Extract all odd numbers. a[a%2==1]
N12. Replace odd numbers with -1. np.where(a%2==1,-1,a)
N13. Stack two arrays vertically then horizontally.
np.vstack([a,b]); np.hstack([a,b])
N14. Compute row-wise and column-wise sums. m.sum(1); m.sum(0)
N15. Find the mean of each row. m.mean(axis=1)
N16. Get indices of the top-3 largest values.
np.argpartition(a,-3)[-3:]
N17. Count nonzero elements. np.count_nonzero(a)
N18. Create an array of 10 evenly spaced values 0–5. np.linspace(0,5,10)
N19. Round an array to 2 decimals. np.round(a,2)
N20. Clip values to [0,100]. np.clip(a,0,100)
N21. Compute cumulative sum. np.cumsum(a)
N22. Find the most frequent value. np.bincount(a).argmax()
N23. Standardize (z-score). (a-a.mean())/a.std()
N24. Create a 3×3 array with random ints 0–9.
np.random.default_rng().integers(0,10,(3,3))
N25. Swap two rows of a matrix. m[[0,1]] = m[[1,0]]
N26. Compute the dot product of two vectors. np.dot(a,b)
N27. Find the determinant of a 2×2 matrix. np.linalg.det(M)
N28. Solve a linear system Ax=b. np.linalg.solve(A,b)
N29. Replace all NaN with 0. np.nan_to_num(a)
N30. Compute pairwise Euclidean distance matrix.
np.sqrt(((a[:,None]-a[None,:])**2).sum(-1))