NumPy square()

square() 函数计算数组元素的平方。

示例

import numpy as np

array1 = np.array([1, 2, 3, 4])

# compute the square of array1 elements result = np.square(array1)
print(result) # Output: [ 1 4 9 16]

square() 语法

square() 的语法是

numpy.square(array, out = None, where = True, dtype = None)

square() 参数

square() 函数接受以下参数

  • array1 - 输入数组
  • out (可选) - 用于存储结果的输出数组
  • where (可选) - 用于在输出数组中对元素进行条件替换
  • dtype (可选) - 输出数组的数据类型

square() 返回值

square() 函数返回一个包含输入数组元素逐个平方的数组。


示例 1:square() 中 dtype 参数的使用

import numpy as np

# create an array
array1 = np.array([1, 2, 3, 4])

# compute the square of array1 with different data types result_float = np.square(array1, dtype=np.float32) result_int = np.square(array1, dtype=np.int64)
# print the resulting arrays print("Result with dtype=np.float32:", result_float) print("Result with dtype=np.int64:", result_int)

输出

Result with dtype=np.float32: [ 1.  4.  9. 16.]
Result with dtype=np.int64: [ 1  4  9 16]

示例 2:square() 中 out 和 where 参数的使用

import numpy as np

# create an array
array1 = np.array([-2, -1, 0, 1, 2])

# create an empty array of same shape of array1 to store the result
result = np.zeros_like(array1)

# compute the square of array1 where the values are positive and store the result in result array np.square(array1, where=array1 > 0, out=result)
print("Result:", result)

输出

Result: [0 0 0 1 4]

这里,

  • where 参数指定了一个条件 array1 > 0,它检查 array1 中的每个元素是否大于零。
  • out 参数设置为 result,这表明结果将存储在 result 数组中。

对于 array1 中不大于 0 的任何元素,结果将为 0

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战