63 lines
2.6 KiB
Python
63 lines
2.6 KiB
Python
import numpy as np
|
|
"""
|
|
Demonstrates array and scalar operations using NumPy, including:
|
|
- Creating 1D and 2D arrays.
|
|
- Performing scalar addition and multiplication on arrays.
|
|
- Element-wise addition, multiplication, and exponentiation between arrays of the same shape.
|
|
- Broadcasting for element-wise operations between arrays of different shapes.
|
|
- Simulating quarterly sales revenue data for two products over two years.
|
|
- Calculating and rounding quarterly revenue growth percentages for each product.
|
|
Prints intermediate and final results for illustration.
|
|
"""
|
|
|
|
array = np.array([1, 2, 3, 4])
|
|
print(f'Array 1D: {array}')
|
|
# Creating a 2D array with 1 row
|
|
array_2d = np.array([[1, 2, 3, 4]])
|
|
|
|
# Scalar addition
|
|
result_add_scalar = array + 2 # Adding 2 to each element
|
|
print(f'\nScalar addition: {result_add_scalar}')
|
|
# Scalar multiplication
|
|
result_mul_scalar = array * 3 # Multiplying each element by 3
|
|
|
|
arr1 = np.array([1, 2, 3, 4])
|
|
arr2 = np.array([5, 6, 7, 8])
|
|
print(f'\nArray 1: {arr1}')
|
|
print(f'Array 2: {arr2}')
|
|
# Element-wise addition
|
|
result_add = arr1 + arr2 # Adding corresponding elements
|
|
print(f'\nElement-wise addition: {result_add}')
|
|
# Element-wise multiplication
|
|
result_mul = arr1 * arr2 # Multiplying corresponding elements
|
|
print(f'Element-wise multiplication: {result_mul}')
|
|
# Element-wise exponentiation (raising to power)
|
|
result_power = arr1 ** arr2 # Raising each element of arr1 to the power of corresponding element in arr2
|
|
print(f'Element-wise exponentiation: {result_power}')
|
|
|
|
|
|
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
|
|
arr2 = np.array([5, 6, 7])
|
|
print(f'\nArray 1:\n{arr1}')
|
|
print(f'Array 2:\n{arr2}')
|
|
# Element-wise addition
|
|
result_add = arr1 + arr2 # Broadcasting arr2 to match the shape of arr1
|
|
print(f'\nElement-wise addition: {result_add}')
|
|
# Element-wise multiplication
|
|
result_mul = arr1 * arr2 # Broadcasting arr2 to match the shape of arr1
|
|
print(f'Element-wise multiplication: {result_mul}')
|
|
# Element-wise exponentiation (raising to power)
|
|
result_power = arr1 ** arr2 # Broadcasting arr2 to match the shape of arr1
|
|
print(f'Element-wise exponentiation:\n{result_power}')
|
|
|
|
#Task:
|
|
# Simulated quarterly sales revenue data for two products in 2021 and 2022
|
|
sales_data_2021 = np.array([[350, 420, 380, 410], [270, 320, 290, 310]])
|
|
sales_data_2022 = np.array([[360, 440, 390, 430], [280, 330, 300, 320]])
|
|
# Calculate the quarterly revenue growth for each product in percents
|
|
revenue_growth = (sales_data_2022 - sales_data_2021) / sales_data_2021 * 100
|
|
# Rounding each of the elements to 2 decimal places
|
|
revenue_growth = np.round(revenue_growth, 2)
|
|
print(f'\nRevenue growth by quarter for each product:\n{revenue_growth}')
|
|
|