📖 How to Use numpy.reshape()
in Python
reshape()
in NumPy is used to change the shape or dimension of an existing array without changing its data. It is one of the most commonly used array manipulation functions in NumPy.
🔧 Syntax of numpy.reshape()
pythonCopyEditnumpy.reshape(a, newshape, order='C')
a
: The original arraynewshape
: Tuple indicating the new shapeorder
: ‘C’ for row-major (default), ‘F’ for column-major
🧪 Example: Reshape a 1D Array into 2D
pythonCopyEditimport numpy as np
arr = np.arange(6) # [0, 1, 2, 3, 4, 5]
reshaped_arr = arr.reshape((2, 3)) # 2 rows, 3 columns
print(reshaped_arr)
Output:
luaCopyEdit[[0 1 2]
[3 4 5]]
🔁 Using -1
in Reshape
The -1
tells NumPy to automatically calculate the dimension based on the original array size.
Example:
pythonCopyEditarr = np.arange(12)
reshaped = arr.reshape((-1, 3))
print(reshaped)
Output:
luaCopyEdit[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
Here, -1
means “figure out how many rows I need”, and 3
is the number of columns.
❓ People Also Ask (with answers)
🔹 What is reshape() in NumPy?
reshape()
is a NumPy function that changes the shape of an array while keeping its data intact. It is useful for preparing data for machine learning models or mathematical operations.
🔹 What does reshape(-1, 1) mean?
It reshapes the array into a column vector. The -1
lets NumPy decide how many rows are needed, and 1
fixes the number of columns.
Example:
pythonCopyEditarr = np.array([1, 2, 3, 4])
arr.reshape(-1, 1)
Output:
luaCopyEdit[[1]
[2]
[3]
[4]]
🔹 Is reshape(-1) the same as flatten?
Not exactly.
reshape(-1)
returns a view (when possible) in 1D.flatten()
always returns a copy in 1D.
Example:
pythonCopyEdita = np.array([[1, 2], [3, 4]])
a.reshape(-1) # [1 2 3 4]
a.flatten() # [1 2 3 4]
Same result, different memory behavior.
🔹 numpy मध्ये reshape() म्हणजे काय?
reshape()
म्हणजे एक NumPy फंक्शन जे आपल्याला एखाद्या array चे आकार (shape) बदलण्याची सुविधा देते. याचा उपयोग डेटा पुन्हा फॉर्मेट करण्यासाठी किंवा विशिष्ट गणिती ऑपरेशन्ससाठी होतो.
⚠️ Common Reshape Errors and Fixes
pythonCopyEditarr = np.arange(5)
arr.reshape((2, 3)) # Error! 2x3 = 6 elements, but arr has 5
Make sure the total number of elements stays the same.
💡 When Should You Use Reshape?
- Data preprocessing in machine learning
- Image reshaping (e.g., from flat arrays to 28×28 pixels)
- Converting time series data for models
- Matrix operations
🏁 Conclusion
The numpy.reshape()
function is a powerful tool that helps you structure your data the way you need it. Whether you’re preparing data for machine learning or simply reorganizing an array, reshape makes it efficient and clean.