Python numpy.square() function returns a new array with the element value as the square of the source array elements. The source array remains unchanged.
Python numpy.square()函数返回一个新数组,该数组的元素值为源数组元素的平方。 源阵列保持不变。
Python numpy.square()示例 (Python numpy.square() Examples)
It’s a utility function to quickly get the square of the matrix elements. Let’s look at the examples of numpy square() function with integer, float, and complex type array elements.
它是一种实用功能,可以快速获取矩阵元素的平方。 让我们看一下带有整数,浮点数和复杂类型数组元素的numpy square()函数的示例。
1. numpy square()int数组 (1. numpy square() int array)
import numpy as np
# ints
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(f'Source Array:\n{array_2d}')
array_2d_square = np.square(array_2d)
print(f'Squared Array:\n{array_2d_square}')
Output:
输出:
Source Array:
[[1 2 3]
[4 5 6]]
Squared Array:
[[ 1 4 9]
[16 25 36]]
2. numpy square()浮点数组 (2. numpy square() floating point array)
import numpy as np
array_2d_float = np.array([1.2, 2.3, 5])
print(f'Source Array:\n{array_2d_float}')
array_2d_float_square = np.square(array_2d_float)
print(f'Squared Array:\n{array_2d_float_square}')
Output:
输出:
Source Array:
[1.2 2.3 5. ]
Squared Array:
[ 1.44 5.29 25. ]
Notice that the integer in the floating-point array has been converted to a floating-point number.
请注意,浮点数组中的整数已转换为浮点数 。
3. numpy square()复数数组 (3. numpy square() complex numbers array)
arr = np.array([1 + 2j, 2 + 3j, 4])
print(f'Source Array:\n{arr}')
arr_square = np.square(arr)
print(f'Squared Array:\n{arr_square}')
Output:
输出:
Source Array:
[1.+2.j 2.+3.j 4.+0.j]
Squared Array:
[-3. +4.j -5.+12.j 16. +0.j]
Here the integer element is converted to a complex number.
在这里,整数元素将转换为复数 。
Reference: API Doc
参考: API文档
翻译自: https://www.journaldev.com/32752/numpy-square-in-python