Scalar operations: numpy in python






Scalar operations in NumPy refer to performing mathematical operations between a scalar (single value) and a NumPy array. These operations are applied element-wise, meaning that the scalar value is combined with each element of the array individually. Scalar operations are a fundamental part of NumPy and are essential for tasks like scaling, shifting, or transforming data within arrays.

Scalar Addition:


import numpy as np 
arr = np.array([1, 2, 3, 4, 5]) 
result = arr + 2 # Add 2 to each element in the array



Scalar Subtraction:

arr = np.array([10, 20, 30, 40, 50]) 
result = arr - 5 # Subtract 5 from each element in the array




Scalar Multiplication:

arr = np.array([2, 4, 6, 8, 10])
result = arr * 3 # Multiply each element by 3




Scalar Division:

arr = np.array([15, 30, 45, 60, 75]) 
result = arr / 5 # Divide each element by 5




These scalar operations are efficient and concise ways to manipulate data in NumPy arrays. They are particularly useful for tasks where you need to apply the same operation to every element in an array without the need for explicit loops.