Discussion 2: August 9th, 2023#
Worksheet #2#
This is a discussion worksheet meant to help you practice with some of the topics we’ve seen up until this point. This worksheet will not be collected for credit, but definitely use it to help learn the following EDA outcomes:
P1. Perform boolean indexing on data frames.
Loading a NumPy array from a pickle file#
Import
numpyusing the usual abbreviationnp, and also import the Pythonpicklemodule (no abbreviation).Notice that there is an attached file
wkst2-starter.pickle. Load the data from that file and store it in the variablearrusing the following code.
with open("wkst2-starter.pickle", "rb") as f:
arr = pickle.load(f)
Check the type of this object using the function
typeand check its dimensions by computing theshapeattribute (no parentheses aftershape). The variablearrshould represent an 8000 by 7 NumPy array.
Practice with Boolean indexing#
Define the variable
xto be the column at index4.Check that
xis a length-8000 NumPy array.How many values in
xare equal to10?Define
arrsubto be the sub-array ofarrcontaining all the rows for which the column at index4is equal to the integer10. Use Boolean indexing witharrandx.What is the shape of
arrsub? Use theshapeattribute again. (It should be7columns, but how many rows?)Define a new variable,
a, to be equal to the number of rows ofarrsub.
Counting rows satisfying a condition using NumPy#
How many rows in
arrcontain the number40? You can usearr == 40to create a Boolean array. From the resulting Boolean array, you can use thesummethod, in particular,.sum(axis=1), to count for each row, how many times40appears. We want to find all the rows where40occurs at least once. Once you have a length-8000 array ofTrueandFalsevalues (withTrueif40occurs in the row and withFalseotherwise). You want to count the number of timesTrueoccurs. Save the result with the variable nameb. (Reality check: the answer should be between 500 and 700.)
Practice with preparing solutions#
You will not be turning in this worksheet, but it is good to practice with how you will be submitting homework.
Store these answers, as well as the names of everyone in your group, as a Python dictionary
ansdict = {"names": [name1, name2, name3], "a": a, "b": b}
The "names" value must be a list, with length the number of group members, and with entries the full names of your group members. The names of your group members should be strings. For example, ["Yasmeen Baki", "Anthony Zamora"].
Save the resulting dictionary in a pickle file using the following code.
with open("wkst2-ans.pickle", "wb") as f:
pickle.dump(ansdict, f)