Contents
Reshaping and Combining Arrays
Data often needs to be reorganized before it can be analyzed. NumPy provides operations for changing array shapes, joining arrays, and dividing data into smaller sections.
Reshaping Arrays
The reshape() method changes an array's dimensions without changing its elements.
import numpy as np
values = np.arange(1, 13)
monthly_data = values.reshape(3, 4)
print(monthly_data)
print(monthly_data.shape)Output:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
The original array contains 12 elements, so it can be reshaped into three rows and four columns. The requested shape must be compatible with the total number of elements.
Combining Arrays
Use np.concatenate() to join arrays along an existing axis.
first_quarter = np.array([12000, 15000, 18000])
second_quarter = np.array([20000, 22000, 25000])
annual_data = np.concatenate(
(first_quarter, second_quarter)
)
print(annual_data)For two-dimensional arrays, the axis determines whether the arrays are joined by rows or columns. Their dimensions must be compatible along the other axes.
Splitting Arrays
The np.split() function divides an array into multiple sections.
sales = np.array([10, 20, 30, 40, 50, 60])
first_half, second_half = np.split(sales, 2)
print(first_half)
print(second_half)The example divides six values into two equal arrays. When using an integer number of sections, the array length must be divisible by that number.
Reshaping and combining operations are useful when organizing numerical inputs, preparing batches, or converting data into a structure expected by a machine learning algorithm.
Python for Data Science
Vishalini A








