v9.1.1
Menu

Reshape NumPy Array

easyFREEArray ManipulationNumPy Array ManipulationNumpy

Problem Statement

Reshape a 1D NumPy array into a 2D array with specified dimensions.

Background

Reshaping is crucial for preparing data for machine learning models. The reshape() method changes array dimensions without changing data.

Your Task

Write a function reshape_array(arr, new_shape) that:

  1. Reshapes the input array to new_shape
  2. Returns a dictionary with:
    • "original_shape": Original shape as list
    • "new_shape": New shape as list
    • "array": Reshaped array as nested list

Output Format

Return a dictionary with exactly these three keys.

Example

Input
arr = np.arange(6), new_shape = (2, 3)
Output
{'original_shape': [6], 'new_shape': [2, 3], 'array': [[0, 1, 2], [3, 4, 5]]}
Reasoning
  • Input: arr is a 1D array of the six integers 0,1,2,3,4,50, 1, 2, 3, 4, 5, so its shape has a single dimension of length 66. new_shape asks for 22 rows and 33 columns.
  • Compatibility: a reshape only rearranges how the same values are grouped, so the element count must match: 2×3=62 \times 3 = 6.
  • Filling order: values are laid out row by row. Row 00 takes the first 33 values 0,1,20, 1, 2; row 11 takes the next 33 values 3,4,53, 4, 5. In general, the value at row ii, column jj is the original element at position 3i+j3i + j (e.g. row 11, column 22 is position 55).
  • Output: original_shape is [6], new_shape is [2, 3], and array is [[0, 1, 2], [3, 4, 5]]: one inner list per row, each of length 33.
  • Notice that the 1D shape is still a one-element list [6], not the bare number 66, and reading the rows of the result left to right gives back 00 to 55 in the original order.

Constraints

  • Use numpy reshape() method
  • new_shape will be compatible with array size
  • Return shapes as lists

Learn this in

More from Numpy

solution.py

Test results

Sign in to run your code against the test cases.