Bird
Raised Fist0
NumPydata~20 mins

Sorting along axes in NumPy - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Sorting Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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)
A
[[1 0 2]
 [2 1 3]
 [3 5 4]]
B
]]4 5 3[ 
]3 1 2[ 
]2 0 1[[
C
[1 0 2]
 [2 1 3]
 [3 5 4]]
D
[[1 0 2]
 [2 1 3]
 [3 4 5]]
Attempts:
2 left
💡 Hint
Remember axis=0 sorts each column independently.
❓ Predict Output
intermediate
2: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)
A
[[[1 2 3]
  [1 4 5]]

 [[0 2 3]
  [6 7 8]]]
B
[[1 2 3]
  [1 4 5]]

 [[0 2 3]
  [6 7 8]]]
C
]]]8 7 6[  
]3 2 0[[ 

]]5 4 1[  
]3 2 1[[[
D
[[[1 2 3]
  [1 4 5]]

 [[0 2 3]
  [6 7 8]]
Attempts:
2 left
💡 Hint
Sorting along axis 2 sorts the innermost arrays.
🔧 Debug
advanced
2: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)
ATypeError: axis must be an integer
BValueError: could not broadcast input array from shape (3,3) into shape (2,3)
CAxisError: axis 3 is out of bounds for array of dimension 2
DSyntaxError: invalid syntax
Attempts:
2 left
💡 Hint
Check the number of dimensions of the array and the axis parameter.
❓ data_output
advanced
2: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)
A2
B6
C9
D3
Attempts:
2 left
💡 Hint
The size attribute gives total number of elements in the array.
🚀 Application
expert
3: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?
Anp.sort(df.values, axis=1)
Bnp.sort(df.values, axis=0)
Cnp.sort(df['Age'], axis=1)
Dnp.sort(df['Age'].values, axis=0)
Attempts:
2 left
💡 Hint
The 'Age' column is a 1D array; axis=0 sorts it correctly.

Practice

(1/5)
1. What does the axis parameter control in numpy.sort?
easy
A. It decides whether to sort rows or columns in an array.
B. It sets the sorting algorithm type.
C. It changes the data type of the array before sorting.
D. It specifies the order of sorting (ascending or descending).

Solution

  1. Step 1: Understand the role of axis in sorting

    The axis parameter tells numpy which direction to sort: 0 means sort each column, 1 means sort each row.
  2. Step 2: Differentiate from other parameters

    Sorting algorithm type and order are controlled by other parameters, not axis.
  3. Final Answer:

    It decides whether to sort rows or columns in an array. -> Option A
  4. Quick Check:

    axis controls direction = A [OK]
Hint: Remember axis=0 sorts columns, axis=1 sorts rows [OK]
Common Mistakes:
  • Confusing axis with sorting order
  • Thinking axis changes data type
  • Assuming axis sets sorting algorithm
2. Which of the following is the correct syntax to sort a 2D numpy array arr along rows?
easy
A. numpy.sort(arr, axis=0)
B. numpy.sort(arr, axis=None)
C. numpy.sort(arr, axis=1)
D. numpy.sort(arr, axis=2)

Solution

  1. Step 1: Identify axis for sorting rows

    In a 2D array, axis=1 means sorting each row individually.
  2. Step 2: Check other options for validity

    Axis=0 sorts columns, axis=None flattens the array into 1D before sorting, axis=2 is invalid for 2D arrays.
  3. Final Answer:

    numpy.sort(arr, axis=1) -> Option C
  4. Quick Check:

    axis=1 sorts rows = B [OK]
Hint: Use axis=1 to sort rows in 2D arrays [OK]
Common Mistakes:
  • Using axis=0 to sort rows
  • Using invalid axis like 2 for 2D arrays
  • Using axis=None which flattens the array
3. What is the output of the following code?
import numpy as np
arr = np.array([[3, 1, 2], [6, 4, 5]])
sorted_arr = np.sort(arr, axis=0)
print(sorted_arr)
medium
A. [[1 2 3] [4 5 6]]
B. [[3 1 2] [6 4 5]] sorted by columns
C. [[3 1 2] [6 4 5]] (unchanged)
D. [[3 1 2] [6 4 5]]

Solution

  1. Step 1: Understand sorting along axis=0

    Sorting with axis=0 sorts each column independently in ascending order.
  2. Step 2: Sort each column of the array

    Columns: [3,6] -> [3,6], [1,4] -> [1,4], [2,5] -> [2,5]. Since columns are already sorted, array remains the same.
  3. Final Answer:

    [[3 1 2] [6 4 5]] sorted by columns -> Option B
  4. Quick Check:

    axis=0 sorts columns = A [OK]
Hint: axis=0 sorts columns top to bottom [OK]
Common Mistakes:
  • Assuming sorting rearranges rows
  • Confusing axis=0 with axis=1
  • Expecting full array sort instead of column-wise
4. The code below throws an error. What is the problem?
import numpy as np
arr = np.array([[1, 3], [2, 4]])
sorted_arr = np.sort(arr, axis=2)
print(sorted_arr)
medium
A. Axis 2 does not exist for a 2D array.
B. The array contains non-numeric data.
C. The sort function requires axis to be None.
D. The array must be 1D to sort.

Solution

  1. Step 1: Check array dimensions

    The array is 2D with shape (2,2), so valid axes are 0 and 1 only.
  2. Step 2: Validate axis parameter

    Using axis=2 is invalid and causes an IndexError because axis 2 does not exist.
  3. Final Answer:

    Axis 2 does not exist for a 2D array. -> Option A
  4. Quick Check:

    Axis must be within array dimensions = C [OK]
Hint: Axis must be less than array dimensions [OK]
Common Mistakes:
  • Using axis out of range
  • Assuming sort only works on 1D arrays
  • Confusing axis with array shape
5. Given a 3D numpy array arr with shape (2, 2, 3), how would you sort the array along the last axis for each 2D slice?
hard
A. np.sort(arr, axis=-2)
B. np.sort(arr, axis=1)
C. np.sort(arr, axis=0)
D. np.sort(arr, axis=2)

Solution

  1. Step 1: Identify the last axis in a 3D array

    For shape (2, 2, 3), axes are 0, 1, 2. The last axis is 2.
  2. Step 2: Use axis=2 to sort along the last axis

    Sorting with axis=2 sorts each 2D slice along the last dimension (length 3).
  3. Final Answer:

    np.sort(arr, axis=2) -> Option D
  4. Quick Check:

    Last axis is 2, so axis=2 sorts last dimension [OK]
Hint: Use axis=-1 or axis=2 for last axis in 3D arrays [OK]
Common Mistakes:
  • Using axis=0 or 1 instead of last axis
  • Confusing negative axis indexing
  • Not matching axis to array shape