Storing Data (Good) Exercises
Exercise 1 (Total recall) ☻
Purely from memory, write short descriptions of the following terms:
Term | Brief description |
---|---|
Subsetting | |
Indexing | |
Slicing | |
Masking |
If you cannot recall the answers, please refer to the notes and put this information you could not recall in italics.
Exercise 2 (Show me the ‘odd’ letters) ☻
= np.array([[1, "A"], [3, "C"], [2, "B"], [4, "D"],
np_array_2d 5, "E"], [7, "G"], [6, "F"], [8, "H"],
[10, "J"], [9, "I"]]) [
Use masking to subset the letters that correspond to the odd numbers. I.e., get the result [A, C, E, G, I]
.
This is a slightly tricky problem because arrays are fussy about type. So, let me give you a recipe to solve this problem.
- Subset all the first elements.
- You should get
array(['1', '3', '2', ..., '10', '9'])
- You should get
- Convert this to integers using
astype(int)
- You must look up how
astype()
works.
- You must look up how
- Use
%
to get the remainder for division by2
.- You should get
array([1, 1, 0, ..., 0, 1])
.
- You should get
- Use the previous result to create a mask that checks if the remainder is zero or not
- You should get
array([True, True, False, ..., False, True])
. - Now you have identified the locations of the odd numbers.
- You should get
- Use the mask and extract the corresponding second elements.
Exercise 3
66, 50, 57, -1, -1],
[[92, -1, 88, -1, -1],
[75, -1, -1, 76, -1],
[-1, 51, 87, -1, -1],
[71, -1, 67, -1, 69]] [
Consider the 2D array shown above. Using your knowledge of NumPy masking, change:
- values below 50 to -1,
- values above 50 to +1, and
- values equal to 50 to 0.
You should end up with:
[[ 1 0 1 -1 -1]
[ 1 -1 1 -1 -1]
[ 1 -1 -1 1 -1]
[-1 1 1 -1 -1]
[ 1 -1 1 -1 1]]