《Python数据分析技术栈》第05章 02 广播、矢量化和算术运算(Broadcasting, vectorization, and arithmetic operations)

02 广播、矢量化和算术运算(Broadcasting, vectorization, and arithmetic operations)

《Python数据分析技术栈》第05章 02 广播、矢量化和算术运算(Broadcasting, vectorization, and arithmetic operations)

广播(Broadcasting)

When we say that two arrays can be broadcast together, this means that their dimensions are compatible for performing arithmetic operations on them. Arrays can be combined using arithmetic operators as long as the rules of broadcasting are followed, which are explained in the following.

当我们说两个数组可以一起广播时,这意味着它们的维数是兼容的,可以对它们进行算术运算。只要遵守广播规则,就可以使用算术运算符组合数组。

Both the arrays have the same dimensions.

两个数组的尺寸相同。

In this example, both arrays have the dimensions 2*6.

在本例中,两个数组的尺寸都是 2*6。

x=np.arange(0,12).reshape(2,6)
y=np.arange(5,17).reshape(2,6)
x*y

One of the arrays is a one-element array.

其中一个数组是单元素数组。

In this example, the second array has only one element.

在本例中,第二个数组只有一个元素。

x=np.arange(0,12).reshape(2,6)
y=np.array([1])
x-y

An array and a scalar (a single value) are combined.

数组和标量(单一值)相结合。

In this example, the variable y is used as a scalar value in the operation.

在本例中,变量 y 在操作中用作标量值。

x=np.arange(0,12).reshape(2,6)
y=2
x/y

We can add, subtract, multiply, and divide arrays using either the arithmetic operators (+/-/* and /), or the functions (np.add, np.subtract, np.multiply, and np.divide)

我们可以使用算术运算符(+/-/* 和 /)或函数(np.add、np.subtract、np.multiply 和 np.divide)对数组进行加、减、乘、除运算。

np.add(x,y)
#Or
x+y

Similarly, you can use np.subtract (or the – operator) for subtraction, np.multiply (or the operator) for multiplication, and np.divide (or the / operator) for division.

同样,您可以使用 np.subtract(或运算符-)来做减法,使用 np.multiply(或运算符)来做乘法,使用 np.divide(或运算符/)来做除法。

矢量化(Vectorization)

Using the principle of vectorization, you can also conveniently apply arithmetic operators on each object in the array, instead of iterating through the elements, which is what you would do for applying operations to items in a container like a list.

利用矢量化原理,您还可以方便地在数组中的每个对象上应用算术运算符,而不是对元素进行迭代,后者是对列表等容器中的项目应用运算符时的做法。

x=np.array([2,4,6,8])
x/2
#divides each element by 2

We can obtain the dot product of two arrays, which is different from multiplying two arrays. Multiplying two arrays gives an element-wise product, while a dot product of two arrays computes the inner product of the elements.

我们可以得到两个数组的点积,这与两个数组相乘不同。两个数组相乘得到的是元素间的乘积,而两个数组的点积计算的是元素间的内积。

你可能感兴趣的:(Python数据分析技术栈,python,数据分析,python,数据分析,numpy)