0
0
NumPydata~5 mins

np.expand_dims() and np.squeeze() in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.expand_dims() do to an array?

np.expand_dims() adds a new axis (dimension) to an array at the specified position. This increases the number of dimensions by one.

Click to reveal answer
beginner
What is the purpose of np.squeeze()?

np.squeeze() removes axes of length 1 from an array, reducing its number of dimensions.

Click to reveal answer
beginner
How would you add a new axis as the first dimension to a 1D array a using np.expand_dims()?

Use np.expand_dims(a, axis=0). This changes shape from (n,) to (1, n).

Click to reveal answer
intermediate
If an array has shape (1, 5, 1), what will be its shape after applying np.squeeze()?

The shape will be (5,) because all axes with length 1 are removed.

Click to reveal answer
intermediate
Can np.squeeze() remove a specific axis only?

Yes, by specifying the axis parameter, np.squeeze() removes the axis only if its length is 1. Otherwise, it raises an error.

Click to reveal answer
What does np.expand_dims(arr, axis=1) do to a 1D array arr of shape (4,)?
AAdds a new axis at position 1, resulting in shape (4, 1)
BAdds a new axis at position 0, resulting in shape (1, 4)
CRemoves all axes of length 1
DDoes nothing
What will be the shape after np.squeeze() is applied to an array of shape (1, 3, 1, 5)?
A(1, 3, 1, 5)
B(3, 5)
C(3, 1, 5)
D(1, 3, 5)
Which function would you use to add a dimension to a 2D array to make it 3D?
Anp.expand_dims()
Bnp.squeeze()
Cnp.reshape()
Dnp.flatten()
What happens if you try np.squeeze() on an axis that is not length 1 when specifying the axis parameter?
AIt removes the axis anyway
BIt adds a new axis
CIt raises an error
DIt ignores that axis and removes others
If you have a 1D array with shape (10,), how can you convert it to shape (10, 1) using np.expand_dims()?
Anp.expand_dims(arr, axis=0)
Bnp.squeeze(arr)
Cnp.reshape(arr, (10, 1))
Dnp.expand_dims(arr, axis=1)
Explain in your own words what np.expand_dims() and np.squeeze() do to an array's shape.
Think about adding or removing dimensions that have size 1.
You got /3 concepts.
    Describe a real-life example where you might need to use np.expand_dims() or np.squeeze() when working with data.
    Consider how images or time series data might need reshaping.
    You got /3 concepts.