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_2d = np.array([[1, "A"], [3, "C"], [2, "B"], [4, "D"],
                        [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.

  1. Subset all the first elements.
    • You should get array(['1', '3', '2', ..., '10', '9'])
  2. Convert this to integers using astype(int)
    • You must look up how astype() works.
  3. Use % to get the remainder for division by 2.
    • You should get array([1, 1, 0, ..., 0, 1]).
  4. 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.
  5. 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:

  1. values below 50 to -1,
  2. values above 50 to +1, and
  3. 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]]
Back to top