Challenge - 5 Problems
Sorting Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of sorting a 2D array along axis 0
What is the output of the following code that sorts a 2D numpy array along axis 0?
NumPy
import numpy as np arr = np.array([[3, 1, 2], [1, 5, 4], [2, 0, 3]]) sorted_arr = np.sort(arr, axis=0) print(sorted_arr)
Attempts:
2 left
💡 Hint
Remember axis=0 sorts each column independently.
✗ Incorrect
Sorting along axis 0 sorts each column independently, so the smallest values in each column come first.
❓ Predict Output
intermediate2:00remaining
Sorting a 3D array along axis 2
What is the output of sorting the following 3D numpy array along axis 2?
NumPy
import numpy as np arr = np.array([[[3, 1, 2], [1, 5, 4]], [[2, 0, 3], [7, 6, 8]]]) sorted_arr = np.sort(arr, axis=2) print(sorted_arr)
Attempts:
2 left
💡 Hint
Sorting along axis 2 sorts the innermost arrays.
✗ Incorrect
Axis 2 is the last axis, so sorting arr along axis 2 sorts each innermost 1D array.
🔧 Debug
advanced2:00remaining
Identify the error in sorting with an invalid axis
What error does the following code raise when trying to sort a 2D numpy array along axis 3?
NumPy
import numpy as np arr = np.array([[3, 1, 2], [1, 5, 4]]) sorted_arr = np.sort(arr, axis=3)
Attempts:
2 left
💡 Hint
Check the number of dimensions of the array and the axis parameter.
✗ Incorrect
The array has 2 dimensions (axes 0 and 1). Axis 3 does not exist, so numpy raises an AxisError.
❓ data_output
advanced2:00remaining
Number of items after sorting a 2D array along axis 1
After sorting the following 2D numpy array along axis 1, how many items are in the resulting array?
NumPy
import numpy as np arr = np.array([[3, 1, 2], [1, 5, 4]]) sorted_arr = np.sort(arr, axis=1) print(sorted_arr.size)
Attempts:
2 left
💡 Hint
The size attribute gives total number of elements in the array.
✗ Incorrect
The original array has shape (2,3), so total elements = 2*3 = 6. Sorting does not change size.
🚀 Application
expert3:00remaining
Sorting a DataFrame column using numpy sort along axis
Given a pandas DataFrame with multiple columns, which numpy sort call correctly sorts the values of the 'Age' column only, without changing the DataFrame shape?
NumPy
import pandas as pd import numpy as np df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 20]}) # Which numpy sort call sorts the 'Age' column values correctly?
Attempts:
2 left
💡 Hint
The 'Age' column is a 1D array; axis=0 sorts it correctly.
✗ Incorrect
df['Age'].values is a 1D array. Sorting along axis=0 sorts the column values. Other options sort the whole DataFrame or use invalid axes.