在 Numpy 中返回一个对角线为 1,其他位置为 0 的二维数组
numpy.eye() 函数返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。这里,第一个参数表示“输出数组的行数”,例如 4 表示 4x4 数组。第二个参数是输出数组的列数。
eye() 函数返回一个所有元素都等于零的数组,除了第 k 个对角线上的元素等于 1。dtype 是返回数组的数据类型。order 指定输出是否应以行主序(C 样式)或列主序(Fortran 样式)存储在内存中。
like 参数是一个参考对象,允许创建不是 NumPy 数组的数组。如果作为 like 传入的类数组支持 __array_function__ 协议,则结果将由它定义。在这种情况下,它确保创建与通过此参数传入的数组对象兼容的数组对象。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组。numpy.eye() 返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。这里,第一个参数表示“输出数组的行数”,例如 4 表示 4x4 数组。第二个参数是输出数组的列数。如果为 None,则默认为第一个参数,即此处为 4x4 -
arr = np.eye(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
# The numpy.eye() returns a 2-D array with 1’s as the diagonal and 0’s elsewhere.
# Here, the 1st parameter means the "Number of rows in the output" i.e. 4 means 4x4 array
# The 2nd parameter is the number of columns in the output. If None, defaults to the 1st parameter i.e. 4x4 here.
arr = np.eye(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