Fundamentals 16 min read

100 Essential NumPy Exercises to Master Array Operations

This article presents a curated collection of 100 NumPy exercises covering array creation, manipulation, mathematical operations, indexing, broadcasting, and advanced techniques, providing concise code examples and explanations to help both beginners and experienced users deepen their understanding of NumPy's capabilities.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
100 Essential NumPy Exercises to Master Array Operations

This collection gathers 100 NumPy exercises sourced from mailing lists, Stack Overflow, and the official documentation, offering quick references and teaching material for array operations.

1. Import the numpy package under the name np

import numpy as np

2. Print the numpy version and the configuration

print(np.__version__)
np.show_config()

3. Create a null vector of size 10

Z = np.zeros(10)
print(Z)

4. Find the memory size of any array

Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))

5. Get the documentation of the numpy add function from the command line

%run `python -c "import numpy; numpy.info(numpy.add)"`

6. Create a null vector of size 10 but set the fifth value to 1

Z = np.zeros(10)
Z[4] = 1
print(Z)

7. Create a vector with values ranging from 10 to 49

Z = np.arange(10,50)
print(Z)

8. Reverse a vector (first element becomes last)

Z = np.arange(50)
Z = Z[::-1]
print(Z)

9. Create a 3x3 matrix with values ranging from 0 to 8

Z = np.arange(9).reshape(3,3)
print(Z)

10. Find indices of non‑zero elements from [1,2,0,0,4,0]

nz = np.nonzero([1,2,0,0,4,0])
print(nz)

11. Create a 3x3 identity matrix

Z = np.eye(3)
print(Z)

12. Create a 3x3x3 array with random values

Z = np.random.random((3,3,3))
print(Z)

13. Create a 10x10 array with random values and find the minimum and maximum

Z = np.random.random((10,10))
Zmin, Zmax = Z.min(), Z.max()
print(Zmin, Zmax)

14. Create a random vector of size 30 and find the mean value

Z = np.random.random(30)
m = Z.mean()
print(m)

15. Create a 2‑D array with 1 on the border and 0 inside

Z = np.ones((10,10))
Z[1:-1,1:-1] = 0
print(Z)

16. Add a border (filled with 0’s) around an existing array

Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)

17. Result of various NumPy expressions

print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf > np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)

18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal

Z = np.diag(1+np.arange(4),k=-1)
print(Z)

19. Create an 8x8 checkerboard pattern

Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)

20. Index of the 100th element in a (6,7,8) array

print(np.unravel_index(99,(6,7,8)))

21. Create a checkerboard 8x8 matrix using tile

Z = np.tile(np.array([[0,1],[1,0]]), (4,4))
print(Z)

22. Normalize a 5x5 random matrix

Z = np.random.random((5,5))
Z = (Z - np.mean(Z)) / np.std(Z)
print(Z)

23. Create a custom dtype describing a color as four unsigned bytes (RGBA)

color = np.dtype([('r', np.ubyte, 1),
                  ('g', np.ubyte, 1),
                  ('b', np.ubyte, 1),
                  ('a', np.ubyte, 1)])

24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

Z = np.dot(np.ones((5,3)), np.ones((3,2)))
print(Z)
# Alternative (Python 3.5+)
Z = np.ones((5,3)) @ np.ones((3,2))
print(Z)

25. Negate all elements between 3 and 8 in a 1‑D array (in place)

Z = np.arange(11)
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)

26. Output of a script using sum and NumPy import

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))

27. Which expressions are legal for an integer vector Z?

Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z

28. Results of various NumPy operations

print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))

29. Round away from zero a float array

Z = np.random.uniform(-10,+10,10)
print(np.copysign(np.ceil(np.abs(Z)), Z))

30. Find common values between two arrays

Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))

31. Ignore all NumPy warnings (not recommended)

# Global ignore
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0
# Restore defaults
_ = np.seterr(**defaults)

... (exercises 32‑50 continue in the same format) ...

Note: Only the first 50 questions are translated here; the remaining 50 will be presented in the next issue.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ArrayNumPyexercisesdata-science
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.