NumPy Reshaping & Resizing Arrays 🔄

Опубликовано: 21 Апрель 2026
на канале: CodeVisium
677
8

1. Reshape arrays with .reshape()
The reshape() function changes the shape of an array without changing its data. It’s useful for converting data into the required dimensions for analysis or modeling.

Long form
import numpy as np
arr = np.arange(12)
reshaped = arr.reshape(3, 4)

One-liner
reshaped = __import__('numpy').arange(12).reshape(3,4)


Here, a 1D array of 12 elements is reshaped into a 3×4 matrix.

2. Flatten arrays with .ravel()
The .ravel() function flattens a multi-dimensional array into 1D. Unlike flatten(), it often returns a view instead of a copy.

Long form
import numpy as np
matrix = np.array([[1, 2], [3, 4]])
flat = matrix.ravel()

One-liner
flat = __import__('numpy').array([[1,2],[3,4]]).ravel()


Here, [[1, 2], [3, 4]] is flattened into [1, 2, 3, 4].

3. Resize arrays with .resize()
The .resize() function changes the shape and size of an array. If the new shape is larger, it fills extra space with repeated data.

Long form
import numpy as np
arr = np.array([1, 2, 3, 4])
np.resize(arr, (3, 4))

One-liner
resized = __import__('numpy').resize(__import__('numpy').array([1,2,3,4]),(3,4))


Here, a 1D array is resized into a 3×4 array with repeated values.

4. Reshape using -1 for automatic dimension calculation
Using -1 in reshape() lets NumPy automatically compute the dimension size.

Long form
import numpy as np
arr = np.arange(12)
reshaped = arr.reshape(-1, 6)

One-liner
reshaped = __import__('numpy').arange(12).reshape(-1,6)


Here, NumPy determines the first dimension automatically, producing a 2×6 array.

5. Convert 1D array into multi-dimensional arrays
You can reshape 1D arrays into higher dimensions for tasks like matrix operations and image data handling.

Long form
import numpy as np
arr = np.arange(8)
reshaped = arr.reshape(2, 2, 2)

One-liner
reshaped = __import__('numpy').arange(8).reshape(2,2,2)


Here, a 1D array of 8 elements becomes a 3D array with shape (2, 2, 2).

5 Interview Questions (with Answers):

Q: What is the difference between reshape() and resize() in NumPy?
A: reshape() changes shape without modifying data size, while resize() can change both shape and size (filling gaps if needed).

Q: What does -1 mean in reshape()?
A: It lets NumPy automatically calculate the missing dimension based on the array’s size.

Q: What’s the difference between .ravel() and .flatten()?
A: .ravel() often returns a view (faster), while .flatten() always returns a copy.

Q: Can reshaping change the order of elements?
A: No, reshaping rearranges elements in row-major (C-style) or column-major (Fortran-style) order but doesn’t shuffle values.

Q: Why is reshaping important in machine learning?
A: It prepares data into the correct shape for models (e.g., converting 1D data into 2D matrices or reshaping images into 4D tensors).

#numpy #Python #DataScience #MachineLearning #Reshape #CodingTips #InterviewPrep