在 NumPy 中返回单位数组
要返回单位数组,请在 Python NumPy 中使用 **numpy.identity()** 方法。单位数组是一个正方形数组,主对角线上为 1。1s 参数是 n x n 输出中行(和列)的数量。该函数返回一个 n x n 数组,其主对角线设置为 1,所有其他元素为 0。
like 参数是一个参考对象,允许创建不是 NumPy 数组的数组。如果作为 like 传入的类数组支持 __array_function__ 协议,则结果将由它定义。在这种情况下,它确保创建与通过此参数传入的数组对象兼容的数组对象。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组。要返回单位数组,请在 Python NumPy 中使用 numpy.identity() 方法。单位数组是一个正方形数组,主对角线上为 1。1s 参数是 n x n 输出中行(和列)的数量 -
arr = np.identity(4)
显示数组 -
print("Array...
", arr)获取数组的类型 -
print("
Array type...
", arr.dtype)
获取数组的形状 -
print("
Array shape...
", arr.shape)获取数组的维度 -
print("
Array Dimensions...
",arr.ndim)
获取数组中元素的数量 -
print("
Array (count of elements)...
",arr.size)示例
import numpy as np
# Create a 2d array
# To return the identity array, use the numpy.identity() method in Python Numpy
# The identity array is a square array with ones on the main diagonal.
# The 1s parameter is the number of rows (and columns) in n x n output
arr = np.identity(4)
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Array type...
", arr.dtype)
# Get the shape of the array
print("
Array shape...
", arr.shape)
# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)
# Get the number of elements of the Array
print("
Array (count of elements)...
",arr.size)输出
Array... [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] Array type... float64 Array shape... (4, 4) Array Dimensions... 2 Array (count of elements)... 16
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP