NumPy - Arithmetic Operations

NumPy - Arithmetic Operations

NumPy provides a wide variety of functions and operators to perform arithmetic operations on NumPy arrays element-wise. These operations are fast and efficient, taking advantage of vectorized operations and broadcasting when possible. Here's a summary of basic arithmetic operations in NumPy:

Addition

To add two arrays, use the + operator or the np.add function:

import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) c = a + b # or np.add(a, b) print(c) # Output: [5 7 9] 

Subtraction

To subtract one array from another, use the - operator or the np.subtract function:

c = a - b # or np.subtract(a, b) print(c) # Output: [-3 -3 -3] 

Multiplication

To multiply two arrays, use the * operator or the np.multiply function. This is element-wise multiplication, not matrix multiplication:

c = a * b # or np.multiply(a, b) print(c) # Output: [ 4 10 18] 

Division

To divide one array by another, use the / operator or the np.divide function:

c = a / b # or np.divide(a, b) print(c) # Output: [0.25 0.4 0.5 ] 

Floor Division

To perform floor division, which rounds down to the nearest integer, use the // operator:

c = a // b print(c) # Output: [0 0 0] 

Modulus

To find the modulus (the remainder after division), use the % operator or the np.mod function:

c = a % b print(c) # Output: [1 2 3] 

Power

To raise the elements of the first array to the powers of the corresponding elements of the second array, use the ** operator or the np.power function:

c = a ** b print(c) # Output: [ 1 32 729] 

Unary operations

You can also apply unary operations like negation:

c = -a print(c) # Output: [-1 -2 -3] 

In-place Operations

To perform an arithmetic operation and assign the result back to the original array, you can use in-place operations:

a += b print(a) # Output: [5 7 9] 

Broadcasting

Broadcasting enables arithmetic operations on arrays of different shapes:

d = np.array([2]) e = a * d # Multiplies every element of 'a' by 2 print(e) # Output: [10 14 18] 

When performing arithmetic operations, make sure that the arrays have compatible shapes or that broadcasting rules apply; otherwise, NumPy will raise a ValueError.

Remember that these operations are element-wise. For matrix operations like matrix multiplication, you would use the @ operator or the np.dot function (or np.matmul for matrix multiplication, which adheres strictly to matrix multiplication rules).


More Tags

fpdf watson-nlu angular-chart sqlresultsetmapping android-viewholder machine-learning hashlib numberformatexception pdf-extraction ng-modal

More Programming Guides

Other Guides

More Programming Examples