Exercises
These exercises check whether shape, dtype, axes, and slicing are becoming ordinary.
Edit the code so it prints the shape (2, 3).
Create a 2 by 3 array
Ready to run.
Hint
Use two inner lists. Each inner list should contain three numbers.
Solution
One fix is:
The array has two rows and three columns, so its shape is (2, 3).
Edit the code so it prints [5 7 9].
Sum each column
Ready to run.
Hint
Column sums use axis=0.
Solution
Use axis=0:
This sums down the rows:
[1 + 4, 2 + 5, 3 + 6] = [5, 7, 9]
Which expression selects the first row of A?
Answer it first, then check.
Hint
The first row is row index 0. Use : for all columns.
Solution
Use:
A[0, :]
The 0 selects the first row. The : keeps all columns.
Edit the code so the output contains A: [[1 2 3] and row: [99 2 3].
Avoid changing the original
Ready to run.
Hint
Call .copy() on the slice:
row = A[0, :].copy()
Solution
Use .copy():
The row is separate, so changing it does not change A.
If A.shape is (4, 2), what is the shape of A.mean(axis=1)?
Answer it first, then check.
Hint
axis=1 reduces across columns and leaves one value per row.
Solution
The shape is:
(4,)
axis=1 removes the second axis. The result keeps one value for each of the
four rows.