Chapter 7: Array-Oriented Programming with Num 1
Array-Oriented Programming with
NumPy
7.1 Introduction
7.1 Q1: Which of the following statements is false?
a. The NumPy (Numerical Python) library is the preferred Python array imple-
mentation—it offers a high-performance, richly functional n-dimensional array
type called ndarray, which you can refer to by its synonym, array.
b. Operations on arrays are up to two orders of magnitude faster than those on
lists.
c. Many popular data science libraries such as Pandas, SciPy (Scientific Python)
and Keras (for deep learning) are built on or depend on NumPy.
d. A strength of NumPy is “array–oriented programming,” which uses functional-
style programming with external iteration to make array manipulations concise
and straightforward, eliminating the kinds of bugs that can occur with the inter-
nal iteration of explicitly programmed loops.
7.2 Creating arrays from Existing Data
7.2 Q1: The NumPy array function receives as an argument an array or other
collection of elements and returns a new array containing the argument’s ele-
ments. Based on the statement:
import numpy as np
numbers = np.array([2, 3, 5, 7, 11])
what type will be output by the following statement?
type(numbers)
a. array
b. ndarray
c. numpy.ndarray
d. numpy
Chapter 7: Array-Oriented Programming with Num 3
c. You can iterate through a multidimensional array as if it were one-dimensional
by using its flat attribute.
d. All of the above statements are true.
7.4 Filling arrays with Specific Values
7.4 Q1: Which of the following statements a), b) or c) is false?
a. NumPy provides functions zeros, ones and full for creating arrays contain–
ing 0s, 1s or a specified value, respectively.
b. The first argument to the functions in Part (a) must be an integer or a tuple of
integers specifying the desired dimensions. For an integer, each function returns
a one-dimensional array with the specified number of elements. For a tuple of
integers, these functions return a multidimensional array with the specified di-
mensions.
c. The array returned by NumPy function full contains elements with the sec-
ond argument’s value and type.
d. All of the above statements are true.
7.5 Creating arrays from Ranges
7.5 Q1: Which of the following statements about NumPy’s linspace function is
false?
a. You can produce evenly spaced floating-point ranges with linspace.
b. The function’s first two arguments specify the starting and ending values in the
range, and the ending value is included in the array.
c. The optional keyword argument num specifies the number of evenly spaced val-
ues to produce—this argument’s default value is 50.
d. All of the above statements are true.
7.5 Q2: Which of the following statements a), b) or c) is false?
a. You can create an array from a range of elements, then use array method re-
shape to transform the one-dimensional array into a multidimensional array.
b. The following code creates an array containing the values from 1 through 20,
then reshapes it into four rows by five columns:
import numpy as np
np.arange(1, 21).reshape(4, 5)
4 Chapter 7: Array-Oriented Programming with NumPy
c. A 24-element one-dimensional array can be reshaped into a 2–by-12, 8–by–3
or 4-by–8 array, and vice versa.
d. All of the above statements are true.
7.5 Q3: Which of the following statements is true with respect to displaying an
array of 1000 items or more?
a. NumPy always drops the middle rows and middle columns from the output.
b. NumPy always drops only the middle rows from the output.
c. NumPy always drops only the middle columns from the output.
d. NumPy drops the middle rows, middle columns or both from the output.
7.6 List vs. array Performance: Introducing %timeit
7.6 Q1: Which of the following statements a), b) or c) is false?
a. Most array operations execute significantly faster than corresponding list op-
erations.
b. With the IPython %timeit magic command, you can time the average duration
of operations.
c. The times displayed by %timeit on one system may vary from those shown on
another.
d. All of the above statements are true.
7.6 Q2: Which of the following statements a), b) or c) is false?
a. The following code uses the random module’s randrange function with a list
comprehension to create a list of six million die rolls and time the operation using
%timeit:
import random
%timeit rolls_list = \
[random.randrange(1, 7) for i in range(0, 6_000_000)]
b. By default, %timeit executes a statement in a loop, and it runs the loop seven
times.
c. After executing the statement, %timeit displays the statement’s average exe-
cution time, as well as the standard deviation of all the executions.
d. All of the above statements are true.
Chapter 7: Array-Oriented Programming with Num 5
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
Answer: d.
7.7 array Operators
7.7 Q1: Which of the following statements a), b) or c) is false?
a. Element-wise operations are applied to every array element, so given an inte-
ger array named numbers, the expression
numbers * 2
multiplies every element by 2, and the expression
numbers ** 3
cubes every element.
b. The expressions in Part (a) do not modify the array numbers.
c. Augmented assignments modify every element in the right operand.
d. All of the above statements are true.
7.7 Q2: Which of the following statements is false?
a. Normally, the arithmetic operations on arrays require as operands two
arrays of the same size and shape.
b. When one operand is a single value, called a scalar, NumPy performs the ele-
ment-wise calculations as if the scalar were an array of the same shape as the
other operand, but with that scalar value in all its elements.
c. If numbers is a five-element integer array, numbers * 2 is equivalent to:
numbers * [2, 2, 2, 2, 2]
d. Broadcasting can only be applied between arrays of the same size and shape,
enabling some concise and powerful manipulations.
7.7 Q3: Which of the following statements is false?
a. You may perform arithmetic operations and augmented assignments between
arrays of the same shape.
b. Arithmetic between arrays of integers and floating-point numbers results in
an array of integers.
c. You can compare arrays with individual values and with other arrays. Com-
parisons are performed element-wise. Such comparisons produce arrays of
6 Chapter 7: Array-Oriented Programming with NumPy
Boolean values in which each element’s True or False value indicates the com-
parison result.
d. The expression numbers >= 13 uses broadcasting to determine whether each
element of numbers is greater than or equal to 13.
7.8 NumPy Calculation Methods
7.8 Q1: Which of the following statements a), b) or c) is false?
a. Calculating the mean of an array totals all of its elements regardless of its
shape, then divides by the total number of elements.
b. You can perform array calculations on each array dimension as well. For ex–
ample, in a two-dimensional array, you can calculate each row’s mean or each col-
umn’s mean.
c. The array methods sum, min, max, mean, std (standard deviation) and var
(variance) are each functional-style programming reductions.
d. All of the above statements are true.
7.8 Q2: Which of the following statements is false?
a. Many calculation methods can be performed on specific array dimensions,
known as the array’s axes. These methods receive an axis keyword argument
that specifies which dimension to use in the calculation, giving you a quick way
to perform calculations by row or column in a two-dimensional array.
b. Assume that you want to calculate the average grade on each exam, represented
by the columns of grades. Specifying axis=0 performs the calculation on all the
row values within each column. Similarly, specifying axis=1 performs the calcu–
lation on all the column values within each individual row.
c. NumPy does not display trailing 0s to the right of the decimal point. Also, it does
not display all element values in the same field width.
d. For a two-dimensional array grades in which each row represents one stu-
dent’s grades on several exams, we can calculate each student’s average grade
with:
grades.mean(axis=1)
8 Chapter 7: Array-Oriented Programming with NumPy
and to select multiple non-sequential rows, use a list of row indices, as in
grades[[1, 3]]
d. All of the above statements are true.
7.10 Q2: Assuming the following array grades:
import numpy as np
grades = np.array([[87, 96, 70], [100, 87, 90],
[94, 77, 90], [100, 81, 82]])
Which of the following statements about two-dimensional arrays is false?
a. You can select subsets of the columns by providing a tuple specifying the row(s)
and column(s) to select.
b. The following code selects only the elements in the first column:
grades[:, 0]
c. You can select consecutive columns using a slice, as in
grades[:, 1:3]
or specific columns using a list of column indices, as in
grades[:, [0, 2]]
d. All of the above statements are true.
7.11 Views: Shallow Copies
7.11 Q1: Objects that “see” the data in other objects, rather than having their own
copies of the data are called ________ objects.
a. subordinate
b. scene
c. view
d. aspect
7.11 Q2: Views are also known as ________ copies.
a. deep
b. secondary
c. reliant
d. shallow
10 Chapter 7: Array-Oriented Programming with NumPy
d. All of the above statements are true.
7.12 Q2: If you need ________ copies of other types of Python objects, pass them to
the ________ module’s ________ function.
a. shallow, shallowcopy, copy
b. deep, deepcopy, copy
c. shallow, copy, copy
d. deep, copy, deepcopy
7.13 Reshaping and Transposing
7.13 Q1: We use array method ________ to produce two-dimensional arrays from
one-dimensional ranges.
a. shape
b. rectangularize
c. reshape
d. None of the above.
7.13 Q2: Which of the following statements a), b) or c) is false?
a. The array methods reshape and resize both enable you to change an array’s
dimensions.
b. Method reshape returns a deep copy of the original array with the new di-
mensions. It does not modify the original array.
c. Method resize modifies the original array’s shape.
d. All of the above statements are true.
7.13 Q3: Which of the following statements a), b) or c) is false?
a. You can take a multidimensional array and flatten it into a single dimension
with the methods flatten and ravel.
b. Method flatten deep copies the original array’s data.
c. Modifying a flattened array does not modify the original array’s data.
d. All of the above statements are true.
12 Chapter 7: Array-Oriented Programming with NumPy
functional-style programming and big data), mathematical operations, visualiza-
tion, data preparation and more.
d. All of the above statements are true.
7.14.1 pandas Series
7.14 Q3: Which of the following statements a), b) or c) is false?
a. NumPy arrays use only zero-based integer indexes.
b. Like arrays, Series use only zero-based integer indexes.
c. Series may have missing data, and many Series operations ignore missing
data by default.
d. All of the above statements are true.
7.14 Q4: Which of the following statements a), b) or c) is false?
a. By default, a Series has integer indexes numbered sequentially from 0.
b. The following code creates a Series of student grades from a list of integers:
import pandas as pd
grades = pd.Series([87, 100, 94])
c. The Series argument in Part (b)’s code also may be a tuple, a dictionary, an
array, another Series or a single value.
d. All of the above statements are true.
7.14 Q5: Which of the following statements a), b) or c) is false?
a. Pandas displays a Series in two-column format with the indexes left aligned
in the left column and the values right aligned in the right column.
b. After listing the Series elements, pandas shows the data type (dtype) of the
underlying array’s elements.
c. It is easier to display a list than a Series in a nice two-column format.
d. All of the above statements are true.
14 Chapter 7: Array-Oriented Programming with NumPy
a. Pandas left-aligns string element values and the dtype for strings is object.
b. The following code calls string method contains on each element to deter-
mine whether the value of each element contains a lowercase ‘a’:
hardware.str.contains(‘a’)
and returns a Series containing bool values indicating the contains method’s
result for each element.
c. The following code uses the Series str attribute to invoke string method up-
per on every Series element, producing a new Series containing the uppercase
versions of each element in hardware:
hardware.str.upper()
d. All of the above statements are true.
7.14.2 DataFrames
7.14 Q10: A pandas ________ is an enhanced two-dimensional array.
a. Series
b. DataFrame
c. dictionary
d. array
7.14 Q11: Which of the following statements a), b) or c) is false?
a. DataFrames can have custom row and column indices, and offer additional op-
erations and capabilities that make them more convenient for many data-science
oriented tasks.
b. DataFrames support missing data.
c. The Series representing each column may contain different element types.
d. All of the above statements are true.
7.14 Q12: Which of the following statements a), b) or c) is false?
a. With DataFrames you can specify custom indexes with the index keyword ar-
gument when we create a DataFrame, as in:
grades_dict = {‘Wally’: [87, 96, 70], ‘Eva’: [100, 87, 90],
‘Sam’: [94, 77, 90], ‘Katie’: [100, 81, 82],
‘Bob’: [83, 65, 85]}
Chapter 7: Array-Oriented Programming with Num 15
import pandas as pd
pd.DataFrame(grades_dict, index=[‘Test1’, ‘Test2’,
‘Test3’])
b. The following code uses the index attribute to change the DataFrame’s in-
dexes from sequential integers to labels:
grades.index = [‘Test1’, ‘Test2’, ‘Test3’]
c. When specifying the indexes, you must provide a one-dimensional collection
that has the same number of elements as there are rows in the DataFrame; oth–
erwise, a ValueError occurs.
d. All of the above statements are true.
7.14 Q13: Assuming the following grades DataFrame:
Wally Eva Sam Katie Bob
Test1 87 100 94 100 83
Test2 96 87 77 81 65
Test3 70 90 90 82 85
which of the following statements a), b) or c) is false?
a. One benefit of pandas is that you can quickly and conveniently look at your data
in many different ways, including selecting portions of the data.
b. The following expression selects the ‘Eva’ column and returns it as a Series:
grades[‘Eva’]
c. If a DataFrame’s column-name strings are valid Python identifiers, you can use
them as attributes. The following code selects the ‘Sam’ column using the Sam
attribute:
grades.Sam
d. All of the above statements are true.
7.14 Q14: Assuming the following grades DataFrame:
Wally Eva Sam Katie Bob
Test1 87 100 94 100 83
Test2 96 87 77 81 65
Test3 70 90 90 82 85
which of the following statements about DataFrames is false?
a. The index can be a slice. In the following slice containing, the range specified
includes the high index (‘Test3′):
16 Chapter 7: Array-Oriented Programming with NumPy
grades.loc[‘Test1’:‘Test3′]
b. When using slices containing integer indices with iloc, the range you specify
excludes the high index (2):
grades.iloc[0:2]
c. To select specific rows, use a tuple rather than slice notation with loc or iloc.
d. All of the above statements are true.
7.14 Q15: Which of the following statements is false?
a. DataFrames have a describe method that calculates basic descriptive statis-
tics for the data and returns them as a two-dimensional array.
b. In a DataFrame, the statistics are calculated by column.
c. Method describe nicely demonstrates the power of array-oriented program-
ming with a functional-style call—Pandas handles internally all the details of cal-
culating these statistics for each column.
d. You can control the precision of floating-point values and other default settings
with pandas’ set_option function.
7.14 Q16: Which of the following statements is false?
a. You can quickly transpose a DataFrame’s rows and columns—so the rows be-
come the columns, and the columns become the rows—by using the T attribute.
b. T returns a transposed copy of the DataFrame.
c. Assuming the following grades DataFrame:
Wally Eva Sam Katie Bob
Test1 87 100 94 100 83
Test2 96 87 77 81 65
Test3 70 90 90 82 85
rather than getting the summary statistics by student, you can get them by test.
Simply call describe on grades.T, as in:
grades.T.describe()
d. To see the average of all the students’ grades on each test, call mean on the T
attribute:
grades.T.mean()