Sunday, 09 February 2025

Performing calculations between a 1-dimensional array and a 2-dimensional array in Python

Python 

Below are some examples of how you can perform calculations between a 1-dimensional array and a 2-dimensional array in Python using NumPy.

Example 1: Element-wise Addition

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Element-wise addition
result = a + b

print(result)

Output:

[[ 5  7  9]
 [ 8 10 12]]

Example 2: Element-wise Multiplication

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Element-wise multiplication
result = a * b

print(result)

Output:

[[ 4 10 18]
 [ 7 16 27]]

Example 3: Dot Product (Matrix Multiplication)

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Dot product (matrix multiplication)
result = np.dot(b, a)

print(result)

Output:

[32 50]

Example 4: Broadcasting with Subtraction

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

## Broadcasting with subtraction
result = b - a

print(result)

Output:

[[3 3 3]
 [6 6 6]]

Example 5: Sum along an axis

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Sum along axis 0 (rows) and add to 1D array
result = b.sum(axis=0) + a

print(result)

Output:

[12 15 18]

Example 6: Outer Product

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Outer product
result = np.outer(a, b)

print(result)

Output:

[[ 4  5  6  7  8  9]
 [ 8 10 12 14 16 18]
 [12 15 18 21 24 27]]

Example 7: Reshape and Multiply

import numpy as np

# 1D array
a = np.array([1, 2, 3])

# 2D array
b = np.array([[4, 5, 6],
              [7, 8, 9]])

# Reshape 1D array to 2D and multiply
a_reshaped = a.reshape(3, 1)
result = np.dot(b, a_reshaped)

print(result)

Output:

[[32]
 [50]]

These examples demonstrate various ways to perform calculations between 1D and 2D arrays in Python using NumPy. The key concept here is broadcasting, which allows NumPy to perform element-wise operations on arrays of different shapes.



Search