返回 Python 中数组输入的逐元素平方
要返回数组输入的逐元素平方,请在 Python 中使用 numpy.square() 方法。该方法返回与 x 形状和数据类型相同的逐元素 x*x。如果 x 是标量,则这是一个标量。
第一个参数 x 是输入数据。第二个参数 out 是存储结果的位置。如果提供,则其形状必须与输入广播到的形状相同。如果未提供或为 None,则返回一个新分配的数组。元组(只能作为关键字参数)的长度必须等于输出的数量。
第三个参数 where,此条件将广播到输入上。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他位置,out 数组将保留其原始值。请注意,如果通过默认 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建一个 numpy 数组。我们添加了 int 类型的元素:
arr = np.array([[25, -50, 75], [-90, 81, 64]])
显示数组:
print("Our Array...\n",arr)检查维度:
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型:
print("\nDatatype of our Array object...\n",arr.dtype)要返回数组输入的逐元素平方,请使用 numpy.square() 方法。该方法返回与 x 形状和数据类型相同的逐元素 x*x。如果 x 是标量,则这是一个标量:
print("\nResult...\n",np.square(arr))示例
import numpy as np
# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[25, -50, 75], [-90, 81, 64]])
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# To return the element-wise square of the array input, use the numpy.square() method in Python
# The method returns the element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.
print("\nResult...\n",np.square(arr))输出
Our Array... [[ 25 -50 75] [-90 81 64]] Dimensions of our Array... 2 Datatype of our Array object... int64 Result... [[ 625 2500 5625] [8100 6561 4096]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP