The broadcast of the NumPy array is powerful, but also confusing, now let's talk about the principles.
Broadcasting principles:
If the back-edge dimension of the two arrays (that is, the dimension from the end of the calculation) corresponds to the length of the axis, or if one side is 1, it is considered broadcast-compatible, and the broadcast is performed on the axis with missing and/or length 1.
The above principle is very important, is the guiding ideology of broadcasting, let's look at the example below.
1. In fact, the operation between the simplest array and the scalar number is broadcast, but we take it for granted.
2. Look again at the next example, and this will all agree that this is a broadcast.
According to the broadcast principle: The shape of the arr1 is (4,1), the shape of the ARR2 is (3), so it will be broadcast on two axes at the same time, the shape of arr1 becomes (4,3), and the arr2 shape becomes (4,3), so the result is (4,3).
In fact, the code describes the things that happen:
3. Similarly, we can get the broadcast of a three-dimensional array
According to broadcast principle analysis: arr1 shape is (3,4,2), arr2 shape is (4,2), their trailing edge axis length is (4,2), so can be broadcast on the 0 axis, arr2 shape into (3,4,2).
The following is a description of the broadcast shape requirements for three-dimensional arrays in each dimension:
All of the above shapes can be broadcast, and you can validate them with the broadcast principle that we're talking about at the outset.
Finally, a more error-prone practical example.
Arr subtracts his average on the 1 axis, will it make an error? See why.
Since Arr.mean (1) produces a shape of (4), according to the broadcast principle, the trailing edge dimension of the smaller array must be 1,
So you need to turn Arr.mean into (4,1), and the results you expect are as follows:
Reference: "Data analysis using Python"
NumPy Array Broadcast