Operations between arrays in Numpy

Operations between arrays in Numpy


1 Array and number operations      [can be directly operated on]

arr = np.array([[1, 2, 3, 2, 1, 4], [5, 6, 1, 2, 3, 1]])
arr + 1
arr / 2

# 可以对比python列表的运算,看出区别
a = [1, 2, 3, 4, 5]
a * 3

2 Array and array operations

arr1 = np.array([[1, 2, 3, 2, 1, 4], [5, 6, 1, 2, 3, 1]])
arr2 = np.array([[1, 2, 3, 4], [3, 4, 5, 6]])

Can the above calculation be performed? The result is not good!

2.1 Broadcast mechanism

When the array is vectorized, the shape of the array is required to be equal . When an arithmetic operation is performed on an array with unequal shapes, a broadcast mechanism will appear, which will expand the array so that the shape attribute value of the array is the same, so that vectorized operations can be performed. The following is an example to illustrate:

arr1 = np.array([[0],[1],[2],[3]])
arr1.shape
# (4, 1)

arr2 = np.array([1,2,3])
arr2.shape
# (3,)

arr1+arr2
# 结果是:
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])

In the above code, the array arr1 has 4 rows and 1 column, and arr2 has 1 row and 3 columns. The two arrays need to be added, and the arrays arr1 and arr2 are expanded according to the broadcast mechanism, so that the arrays arr1 and arr2 become 4 rows and 3 columns.

The following is a diagram to describe the process of expanding the array by the broadcast mechanism:

The broadcast mechanism implements the operation of two or more arrays. Even if the shapes of these arrays are not exactly the same, it only needs to meet any one of the following conditions.

  • 1. A certain dimension of the array is of equal length.
  • 2. A certain dimension of one of the arrays is 1.

The broadcast mechanism needs to expand the small-dimensional array so that it has the same shape value as the largest-dimensional array in order to use element-level functions or operators to perform operations.

If it is like this, there is no match:

A  (1d array): 10
B  (1d array): 12
A  (2d array):      2 x 1
B  (3d array):  8 x 4 x 3

Thinking: Can the following two ndarrays be operated on?

arr1 = np.array([[1, 2, 3, 2, 1, 4], [5, 6, 1, 2, 3, 1]])
arr2 = np.array([[1], [3]])

3 summary

  • Array operation, satisfies the broadcast mechanism, it is OK
    • 1. Equal dimensions
    • 2.shape (the corresponding place is 1, which is also possible)

Guess you like

Origin blog.csdn.net/weixin_44799217/article/details/113854173