Numpy - Basic operations

 NumPy allows for performing various arithmetic operations on arrays, which are applied elementwise. Here's a breakdown of basic operations with examples:

  1. Elementwise Arithmetic Operations:

a = np.array([20, 30, 40, 50])
b = np.arange(4)
c = a - b
print(c)  # Output: array([20, 29, 38, 47])

b_squared = b**2
print(b_squared)  # Output: array([0, 1, 4, 9])

scaled_sine = 10 * np.sin(a)
print(scaled_sine)  # Output: array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])

comparison = a < 35
print(comparison)  # Output: array([ True,  True, False, False])


Matrix Operations:

A = np.array([[1, 1], [0, 1]]) B = np.array([[2, 0], [3, 4]]) elementwise_product = A * B print(elementwise_product) # Output: array([[2, 0], [0, 4]]) matrix_product = A @ B print(matrix_product) # Output: array([[5, 4], [3, 4]]) dot_product = A.dot(B) print(dot_product) # Output: array([[5, 4], [3, 4]])


n-place Operations:

a = np.ones((2, 3), dtype=int) b = rg.random((2, 3)) a *= 3 print(a) # Output: array([[3, 3, 3], [3, 3, 3]]) b += a print(b) # Output: array([[3.51182162, 3.9504637 , 3.14415961], [3.94864945, 3.31183145, 3.42332645]])


Type Casting:

a = np.ones(3, dtype=np.int32) b = np.linspace(0, pi, 3) c = a + b print(c) # Output: array([1. , 2.57079633, 4.14159265])


Unary Operations:

a = rg.random((2, 3)) print(a.sum()) # Output: 3.1057109529998157 print(a.min()) # Output: 0.027559113243068367 print(a.max()) # Output: 0.8277025938204418



Operations Along Axes:

b = np.arange(12).reshape(3, 4) print(b.sum(axis=0)) # Output: array([12, 15, 18, 21]) print(b.min(axis=1)) # Output: array([0, 4, 8]) print(b.cumsum(axis=1)) # Output: array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]])


These basic operations make NumPy a powerful tool for numerical computing and data manipulation.



Comments

Popular posts from this blog

Adding constants to numpy array?