Can we perform operations between 1-D and 2-D NumPy Arrays?


#1

Question

Can we perform operations between 1-D and 2-D NumPy Arrays?

Answer

Yes, when performing an operation between a 1-D and a 2-D NumPy Array, it will essentially perform the operation on the 1-D array with each row of the 2-D Array individually.

As a result, it is only possible if the number of elements for every row in both Arrays match.

For example, these two arrays have 2 elements in each row, so you can perform an operation on them.

# When we perform an operation on these arrays, 
# it is essentially running the operation 
# on each row of the 2-D list with the 1-D list.
arr1 = np.array([[1, 1], [2, 2], [3, 3]])
arr2 = np.array([10, 10])

arr1 * arr2
# The result of running the above is
# [[10 10]
#  [20 20]
#  [30 30]]