NumPy Array Broadcast

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.