38 lines
1.8 KiB
Python
38 lines
1.8 KiB
Python
import numpy as np
|
|
"""
|
|
This script demonstrates how to concatenate NumPy arrays using `np.concatenate` for both 1D and 2D arrays.
|
|
Examples included:
|
|
- Concatenating two 1D arrays along their only axis.
|
|
- Concatenating two 2D arrays along axis 0 (rows) and axis 1 (columns).
|
|
- Combining simulated quarterly sales data for two products across two years by concatenating along columns.
|
|
Variables:
|
|
- array1, array2: Example arrays for demonstration.
|
|
- concatenated_array: Result of concatenating 1D arrays.
|
|
- concatenated_array_rows: Result of concatenating 2D arrays along rows.
|
|
- concatenated_array_columns: Result of concatenating 2D arrays along columns.
|
|
- sales_data_2021, sales_data_2022: Simulated sales data arrays.
|
|
- combined_sales_by_product: Combined sales data for both years by product.
|
|
Prints the results of each concatenation operation.
|
|
"""
|
|
array1 = np.array([1, 2, 3])
|
|
array2 = np.array([4, 5, 6])
|
|
# Concatenating 1D arrays along their only axis 0
|
|
concatenated_array = np.concatenate((array1, array2))
|
|
print(concatenated_array)
|
|
|
|
|
|
array1 = np.array([[1, 2], [3, 4]])
|
|
array2 = np.array([[5, 6], [7, 8]])
|
|
# Concatenating along the axis 0 (rows)
|
|
concatenated_array_rows = np.concatenate((array1, array2))
|
|
print(f'Axis = 0:\n{concatenated_array_rows}')
|
|
# Concatenating along the axis 1 (columns)
|
|
concatenated_array_columns = np.concatenate((array1, array2), axis=1)
|
|
print(f'Axis = 1:\n{concatenated_array_columns}')
|
|
|
|
# Simulated data for quarterly sales of two products in 2021 and 2022
|
|
sales_data_2021 = np.array([[350, 420, 380, 410], [270, 320, 290, 310]])
|
|
sales_data_2022 = np.array([[370, 430, 400, 390], [280, 330, 300, 370]])
|
|
# Concatenate the sales data for both products by columns
|
|
combined_sales_by_product = np.concatenate((sales_data_2021, sales_data_2022), axis=1)
|
|
print(f'Combined sales by product:\n{combined_sales_by_product}') |