Concatenating
Why Concatenating?
Concatenating is an another powerful feature in NumPy that allows you to combine multiple arrays into a single array.
This example demonstrates how concatenation can be used to combine multiple arrays into a single array, and how to use the np.vstack()
and np.hstack()
functions to concatenate arrays vertically and horizontally, respectively.
import numpy as np
# Create two NumPy arrays with sales data
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Concatenate the two arrays
concatenated_array = np.concatenate((array1, array2))
print("Concatenated Array: ", concatenated_array)
# Output: [1 2 3 4 5 6]
# Create two NumPy arrays with sales data
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
# Concatenate the two arrays vertically
vertically_concatenated_array = np.vstack((array1, array2))
print("Vertically Concatenated Array: \n", vertically_concatenated_array)
# Output:
# [[1 2]
# [3 4]
# [5 6]
# [7 8]]
# Create two NumPy arrays with sales data
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])
# Concatenate the two arrays horizontally
horizontally_concatenated_array = np.hstack((array1, array2))
print("Horizontally Concatenated Array: \n", horizontally_concatenated_array)
# Output:
# [[1 2 5 6]
# [3 4 7 8]]
A real-world example:
Suppose we have two datasets of sales data for a company, one for the first half of the year and one for the second half of the year. We can use concatenation to combine these two datasets into a single array.
import numpy as np
# Create two NumPy arrays with sales data
first_half_sales = np.array([
[100, 200, 300], # January
[120, 250, 320], # February
[150, 300, 350], # March
[180, 350, 380], # April
[200, 400, 420], # May
[220, 450, 450] # June
])
second_half_sales = np.array([
[250, 500, 550], # July
[280, 550, 580], # August
[300, 600, 650], # September
[320, 650, 680], # October
[350, 700, 750], # November
[380, 750, 780] # December
])
# Concatenate the two arrays
annual_sales = np.concatenate((first_half_sales, second_half_sales))
print("Annual Sales: \n", annual_sales)
key concepts
Here are some key concepts to keep in mind when using concatenation:
np.concatenate((array1, array2, ...))
: This syntax is used to concatenate multiple arrays into a single array.np.vstack((array1, array2, ...))
: This syntax is used to concatenate multiple arrays vertically (i.e., along the rows).np.hstack((array1, array2, ...))
: This syntax is used to concatenate multiple arrays horizontally (i.e., along the columns).