Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

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() and array_split().
  • Use hsplit() and vsplit() 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.

import numpy as np group_a = np.array([10, 20, 30]) group_b = np.array([40, 50, 60]) combined = np.concatenate((group_a, group_b)) print(combined)

Output:

[10 20 30 40 50 60]

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.

Group A Group B 10 20 30 40 50 60 Combined Array 10 20 30 40 50 60

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.

import numpy as np first = np.array([1, 2, 3]) second = np.array([4, 5, 6]) result = np.concatenate((first, second)) print(result) print("Shape:", result.shape)

Output:

[1 2 3 4 5 6] Shape: (6,)

Concatenating Two-Dimensional Arrays

import numpy as np first = np.array([ [1, 2], [3, 4] ]) second = np.array([ [5, 6], [7, 8] ]) vertical_result = np.concatenate((first, second), axis=0) horizontal_result = np.concatenate((first, second), axis=1) print("Axis 0:") print(vertical_result) print("Axis 1:") print(horizontal_result)

Output:

Axis 0: [[1 2] [3 4] [5 6] [7 8]] Axis 1: [[1 2 5 6] [3 4 7 8]]
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.
Remember: Concatenation joins arrays along an existing axis. The other dimensions must be compatible.

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.

import numpy as np row_a = np.array([[10, 20, 30]]) row_b = np.array([[40, 50, 60]]) result = np.vstack((row_a, row_b)) print(result) print("Shape:", result.shape)

Output:

[[10 20 30] [40 50 60]] Shape: (2, 3)
First Array Second Array 10 20 30 40 50 60 Vertically Stacked 10 20 30 40 50 60 Shape: (2, 3) The second row is placed below the first row

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.

import numpy as np left = np.array([ [1, 2], [3, 4] ]) right = np.array([ [5, 6], [7, 8] ]) result = np.hstack((left, right)) print(result) print("Shape:", result.shape)

Output:

[[1 2 5 6] [3 4 7 8]] Shape: (2, 4)
Tip: Use 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.

import numpy as np first = np.array([1, 2, 3]) second = np.array([4, 5, 6]) result_axis0 = np.stack((first, second), axis=0) result_axis1 = np.stack((first, second), axis=1) print("Axis 0:") print(result_axis0) print("Axis 1:") print(result_axis1)

Output:

Axis 0: [[1 2 3] [4 5 6]] Axis 1: [[1 4] [2 5] [3 6]]
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.
Important: Arrays passed to 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.

import numpy as np values = np.array([10, 20, 30, 40, 50, 60]) parts = np.split(values, 3) for part in parts: print(part)

Output:

[10 20] [30 40] [50 60]
Original Array 10 20 30 40 50 60 10 20 30 40 50 60 Part 1 Part 2 Part 3

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.

import numpy as np values = np.array([1, 2, 3, 4, 5, 6]) first, second, third = np.split(values, 3) print(first) print(second) print(third)

Output:

[1 2] [3 4] [5 6]

Splitting at Specific Positions

import numpy as np values = np.array([10, 20, 30, 40, 50, 60, 70]) parts = np.split(values, [2, 5]) for part in parts: print(part)

Output:

[10 20] [30 40 50] [60 70]

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.

import numpy as np values = np.array([10, 20, 30, 40, 50, 60, 70]) parts = np.array_split(values, 3) for part in parts: print(part)

Output:

[10 20 30] [40 50] [60 70]
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.
Tip: If the array length is not evenly divisible by the requested number of sections, use 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.

import numpy as np data = np.array([ [1, 2, 3, 4], [5, 6, 7, 8] ]) left, right = np.hsplit(data, 2) print("Left section:") print(left) print("Right section:") print(right)

Output:

Left section: [[1 2] [5 6]] Right section: [[3 4] [7 8]]

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.

import numpy as np data = np.array([ [10, 20], [30, 40], [50, 60], [70, 80] ]) top, bottom = np.vsplit(data, 2) print("Top section:") print(top) print("Bottom section:") print(bottom)

Output:

Top section: [[10 20] [30 40]] Bottom section: [[50 60] [70 80]]
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.

import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6]]) # Valid vertical concatenation: result = np.concatenate((a, b), axis=0) print(result) print(result.shape)

Output:

[[1 2] [3 4] [5 6]] (3, 2)
Common mistake: Attempting to concatenate arrays whose non-concatenated dimensions do not match will raise a 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:

  1. Create two two-dimensional arrays representing separate groups.
  2. Combine the arrays vertically using vstack().
  3. Combine compatible arrays horizontally using hstack().
  4. Use concatenate() to join arrays along axis 0.
  5. Split the combined array into equal row sections.
  6. Display the shape of each resulting array.

Sample Solution

import numpy as np group_a = np.array([ [78, 85], [88, 76] ]) group_b = np.array([ [90, 82], [91, 87] ]) combined = np.vstack((group_a, group_b)) print("Combined marks:") print(combined) print("Combined shape:", combined.shape) left_subjects = combined[:, :1] right_subjects = combined[:, 1:] side_by_side = np.hstack((left_subjects, right_subjects)) print("Horizontally stacked:") print(side_by_side) first_half, second_half = np.vsplit(combined, 2) print("First half:") print(first_half) print("Second half:") print(second_half)

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.