Stacking and Splitting Arrays
Learn how to combine multiple NumPy arrays into larger arrays and divide arrays into smaller sections. Explore concatenate(), vstack(), hstack(), stack(), split(), hsplit(), and vsplit() with practical examples and real-world data processing scenarios.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand the difference between stacking and splitting arrays.
- Combine arrays using
concatenate(). - Stack arrays vertically with
vstack(). - Stack arrays horizontally with
hstack(). - Create a new dimension using
stack(). - Divide arrays using
split()andarray_split(). - Use
hsplit()andvsplit()for two-dimensional arrays. - Identify shape mismatches and select the appropriate operation.
2. What Is Array Stacking?
Array stacking means combining two or more arrays into a larger array. It is useful when data is collected from different sources and must be brought together for analysis.
For example, marks collected from separate student groups can be combined into one dataset. NumPy provides several functions for combining arrays, and each function handles dimensions differently.
Output:
In this example, the values from the second array are placed after the values from the first array. The result is one array containing all six elements.
Stacking and concatenation bring separate arrays together into a combined dataset.
3. Combining Arrays with concatenate()
The np.concatenate() function joins arrays along an
existing axis. For one-dimensional arrays, the values are joined
end to end. For multidimensional arrays, the arrays must have
compatible shapes along the dimensions that are not being joined.
Output:
Concatenating Two-Dimensional Arrays
Output:
| Expression | Result Shape | Effect |
|---|---|---|
concatenate((a, b), axis=0) |
(4, 2) |
Adds rows when column counts match. |
concatenate((a, b), axis=1) |
(2, 4) |
Adds columns when row counts match. |
4. Vertical Stacking with vstack()
The np.vstack() function stacks arrays vertically.
For two-dimensional arrays, this places one array below another.
Their column counts must match.
Output:
vstack() combines arrays vertically into a larger array.
5. Horizontal Stacking with hstack()
The np.hstack() function stacks arrays horizontally.
For two-dimensional arrays, this places columns from one array
beside columns from another array. Their row counts must match.
Output:
vstack() when you want to
add rows and hstack() when you want to add columns.
Always check the shapes of the arrays before combining them.
6. Understanding stack()
The np.stack() function combines arrays by introducing
a new axis. This is different from concatenate(),
which joins arrays along an existing axis.
Output:
| Operation | Output Shape | Explanation |
|---|---|---|
stack((a, b), axis=0) |
(2, 3) |
Creates a new first axis for the two arrays. |
stack((a, b), axis=1) |
(3, 2) |
Creates a new second axis. |
stack()
must have the same shape before the new axis is added.
7. What Is Array Splitting?
Array splitting divides an existing array into multiple smaller arrays. It is useful when a dataset needs to be separated into training and testing portions, divided into groups, or processed in smaller sections.
NumPy provides split(), array_split(),
hsplit(), and vsplit() for different
splitting requirements.
Output:
Splitting divides an array into smaller sections while preserving the elements.
8. Using split()
The np.split() function divides an array into a
specified number of equal sections or uses specified split
positions. When an integer number of sections is supplied, the
array must be divisible into equal parts.
Output:
Splitting at Specific Positions
Output:
The positions indicate where splitting occurs. The first split happens before index 2, and the second happens before index 5. The final section contains the remaining elements.
9. Using array_split()
Unlike split(), the np.array_split()
function allows an array to be divided into sections that are
not all equal in size. It is useful when the total number of
elements cannot be divided evenly.
Output:
| Function | Behavior | Use Case |
|---|---|---|
split() |
Requires equal sections when an integer number of sections is specified. | Dividing evenly sized datasets. |
array_split() |
Allows sections with slightly different sizes. | Dividing datasets with uneven element counts. |
array_split()
when uneven sections are acceptable.
10. Horizontal Splitting with hsplit()
The np.hsplit() function splits a two-dimensional
array along its columns. It is equivalent to splitting along
axis 1 for the relevant two-dimensional array.
Output:
The original array has four columns. Splitting it into two equal sections creates two arrays, each containing two columns.
11. Vertical Splitting with vsplit()
The np.vsplit() function splits a two-dimensional
array along its rows. It is equivalent to splitting along
axis 0 for a two-dimensional array.
Output:
| Function | Splitting Direction | Requirement for Equal Sections |
|---|---|---|
hsplit() |
Across columns | Column count must be divisible by the number of sections. |
vsplit() |
Across rows | Row count must be divisible by the number of sections. |
array_split() |
Along a selected axis | Sections may have different sizes. |
12. Common Errors and Best Practices
Check Array Shapes Before Stacking
When combining two-dimensional arrays horizontally, the row counts must match. When combining them vertically, the column counts must match.
Output:
ValueError. Inspect their shapes before joining them.
Quick Reference
| Requirement | Recommended Function |
|---|---|
| Join arrays along an existing axis. | np.concatenate() |
| Place arrays one below another. | np.vstack() |
| Place arrays side by side. | np.hstack() |
| Combine arrays along a new axis. | np.stack() |
| Divide into equal sections. | np.split() |
| Divide when section sizes may differ. | np.array_split() |
| Split columns of a 2D array. | np.hsplit() |
| Split rows of a 2D array. | np.vsplit() |
13. Practical Activity
Activity: Combine and Divide Student Marks
Samadhan, Pradnya, and Samiksha are working with student assessment data. Two groups have submitted marks, and the institute needs to combine the data, inspect its shape, and separate it into smaller sections for analysis.
Tasks:
- Create two two-dimensional arrays representing separate groups.
- Combine the arrays vertically using
vstack(). - Combine compatible arrays horizontally using
hstack(). - Use
concatenate()to join arrays along axis 0. - Split the combined array into equal row sections.
- Display the shape of each resulting array.
Sample Solution
Expected key results:
- Combined shape:
(4, 2) - Horizontally stacked shape:
(4, 2) - Each half has shape
(2, 2). - The combined dataset retains all eight original marks.
Summary
In this lesson, we learned how to combine NumPy arrays using concatenate(), vstack(), hstack(), and stack(). We explored how concatenation joins arrays along an existing axis, while stack() introduces a new axis. We also learned how to divide arrays using split(), array_split(), hsplit(), and vsplit().
These operations are useful when combining datasets from multiple sources, organizing student marks, separating columns, and dividing large arrays into manageable sections. Always check array shapes and dimension compatibility before stacking or splitting. Choosing the appropriate function helps prevent shape errors and keeps numerical data organized for further analysis.