--- title: "NumPy Examples -- Practice Questions Make You an Expert" date: "2022-02-16" categories: - "python-practice" tags: - "featured" coverImage: "numpy.png" --- # NumPy Examples -- Practice Questions Make You an Expert Have you learned some NumPy, but now your learning has stalled because you don't have any practice questions or exercises to review what you've learned? This practice set of forty-five NumPy examples features NumPy questions in varying degrees of difficulty. Some are very common examples of NumPy arrays, others get into some more advanced features. The exercises to challenge you are all in this article, but you'll also find full solutions so you can compare your answers. This example set features several questions that I worked on recently to review and improve my knowledge of NumPy -- the excellent, high-performance n-dimensional array library that is a core pillar of the Python data science stack. These questions and exercises range from those that I could get right or code off the top of my head to challenging questions that I had no idea about when I worked on them (or made mistakes on the first time I tried). So don't feel bad if some of these are hard, or you can't finish all of them. That said, they will be simpler if you have some background in NumPy. If you need some materials for making a start on NumPy and Python data science, see our article, [How to Practice Python: Data Science and Pandas](https://codesolid.com/how-to-practice-python-data-science-and-pandas/). ## Finding the Solutions For those I didn't know the answer to, I used a combination of Google and [The NumPy API Reference](https://numpy.org/doc/stable/reference/index.html) to try to work out the solution, so yes, you should research these if you want to practice! The exercises selected here cover many of the features of NumPy, but it's not meant to be exhaustive. For example, we don't cover the linear algebra features in `numpy.linalg`. In the exercises that follow, any unqualified references to an "array" mean a NumPy array, not a native Python array. References to "np" refer to the NumPy package in the usual way it is aliased: "`import numpy as np`". Good luck, and let me know how it goes! Update: We've added a solution dropdown to each question so you don't need to switch back and forth between the exercises and the solution set. That said, it's still a good idea to try to recall the answer or look in the NumPy API reference, and use the solution links as a last resort! ## Creating Simple One-Dimensional NumPy Arrays NumPy has several functions that will return an n-Dimensional array. These exercises ask you to recall these functions to create arrays with only one dimension. 1. Using a NumPy function, how would you create a one-dimensional NumPy array of the numbers from 10 to 100, counting by 10? Show Solution ```python np.arange(10, 110, 10) # Creates # array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) ``` 2. How could you create the same NumPy array using a Python range and a list? Show Solution ```python np.array([i for i in range(10, 110, 10)]) # Creates # array([ 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]) ``` 3. What happens if you pass no arguments to the np.array()? Show Solution It raises a TypeError exception, complaining that the required argument, 'object" is missing. NumPy arrays can be constructed from an iterable, as we've shown. If passed a scalar such as an integer, they'll create a "zero-dimensional array" -- that is, an array with only one element. 4. How might you create a NumPy array of the capital letters, A-Z? Show Solution ```python from string import ascii_uppercase np.array(list(ascii_uppercase)) # Creates: # array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', # 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], # dtype=' 1). 31. What is the result of `one_dim > 2` ? Show Solution Using a comparison operator on a NumPy array vectorizes the comparison, so what's returned is an array of booleans that satisfy the comparison. Since for this expression the last three values satisfy the comparison, the array returned is: ```bash array([False, False, True, True, True]) ``` 32. For NumPy arrays, logical operations are done with the operators "`&`" and "`|`", rather than the usual Python "and" and "or". Given that, what would be the result of this expression? `(one_dim > 4) | (one_dim == 1)` Show Solution Once again, we're looking for the results that satisfy the comparison, so the numbers that are either greater than four or equal to one. This matches the first and last element of the array, so our vectorized answer is: ```bash array([ True, False, False, False, True]) ``` 33. What is the result of this expression: `-one_dim` Show Solution Here again, the negation operator is vectorized over the whole NumPy array, giving us: ```bash array([-1, -2, -3, -4, -5]) ``` 34. `np.absolute` take the absolute value of each element. Given that, what would the result be of the following expression: `np.absolute(-(one_dim[3:])` Show Solution Here we're not concerned with whether the value of the target array is positive or negative, `np.absolute` gets us an absolute magnitude. But we also need to evaluate the slice expression here, which returns the values from index 3 to the end of the array. So the correct value for this exercise is: ```bash array([4, 5]) ``` 35. This exercise shows the use of one of NumPy's sequence functions, which operate on the whole array rather than per element. What is returned by `one_dim.sum()` ? Show Solution See, not all of these questions are brainbusters -- good for you if you guessed that `numpy.array.sum` simply adds up all the values in the array, returning 15. The sum function in Python does the same thing for lists, by the way: ```bash numbers = [x for x in range(1,6)] print(sum(numbers)) # Output 15 ``` For a list or array of this size, the difference hardly matters, but being implemented in C, NumPy's performance gains really make a difference on large arrays or matrices. 36. Break out those pictures of the unit circle for this one, for some trigonometry so simple an ex-history major can do it -- well at least I can on a good day. As background, we can round numbers to a decimal precision using `np.around(arr, num_decimals)`, and get the sine of an angle (in radians) using `np.sin`. So with that, given the following array of angles in radians: `arr = np.array([0., .5, 1.0, 1.5, 2.0]) * np.pi` What does the following display: `print(np.int32(np.sin(arr)))` Note: the fact that we're able to cast to an integer is a bit of a hint, but otherwise, we can end up with some pretty surprising rounding errors! Show Solution OK, this one was a bit more challenging, but if you happened to remember (or look up), that on the unit circle the sin function represents the vertical (y-axis) component of the angle, most of it falls into place. At pi \* 0, we're at the point (1,0), at pi \*.5 (one-half pi), we're at the point (0, 1), and so forth. So our output ends up looking like this: \[ 0 1 0 -1 0\] 37. For the defined above in #36, what are the values for: `np.around(np.cos(arr), 0)` Show Solution If #36 was concerned with the y-axis component of the points going once around the unit circle every 90 degrees, this one asked you for the x-axis component (the cosine). The solution is: \[ 1 0 -1 0 1\] ## Working with Files 38. You're asked to save the following two arrays as is to a file, "data.npz". The arrays should be named as they are here in the file. How could you do it? ```python people = np.array(["John", "Jennifer", "Helen", "Miryam"]) languages = np.array([2, 2, 1, 1]) ``` Show Solution ```python np.savez("data.npz", people=people, languages=languages) ``` 39. Assuming you saved the file, "data.npz", in #38, how could you reload the arrays into two new variables: `people2` and `languages2`? Show Solution ```python arrays = np.load("data.npz") people2 = arrays["people"] languages2 = arrays["languages"] print(people2) print(languages2) # Output # ['John' 'Jenniffer' 'Helen' 'Miryam'] # [2 2 1 1] ``` 40. Given `arr = np.arange(1,13).reshape(3,4)` How could you save it to a CSV file, "myrray.csv". Show Solution ```python arr = np.arange(1,13).reshape(3,4) np.savetxt("myarray.csv", arr, delimiter=",") ``` 41. Given the CSV file saved in #40, how could you load it back into a variable, `arr2`? Show Solution ```python arr2 = np.loadtxt("myarray.csv", delimiter=",") ``` ## NumPy String Functions Next, let's relax a little with some simple character-oriented (string) functions, from the `np.char` package. Some of these are simply vectorized (element-wise) versions of the Python standard library functions. Proving that every Python blog gets around to the Lumberjack Song eventually, here's the NumPy array we'll use for the problems in this section: ```python lumberjack = np.array("I'm a lumberjack and I'm OK I sleep all night and I work all day".split(" ")) lumberjack # Output array(["I'm", 'a', 'lumberjack', 'and', "I'm", 'OK', 'I', 'sleep', 'all', 'night', 'and', 'I', 'work', 'all', 'day'], dtype='=5) print(search_results) print(lumberjack[search_results]) ``` Show Solution ```bash [2 7 9] ['lumberjack' 'sleep' 'night'] ```