在 Numpy 中返回一个二维数组,其上对角线为 1,其他位置为 0
numpy.eye() 函数返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。这里,第一个参数表示“输出中的行数”,例如 4 表示 4x4 数组。第二个参数是输出中的列数。如果为 None,则默认为第一个参数,即这里为 4x4。第三个参数即 K 是对角线的索引:0(默认值)表示主对角线,正值表示上对角线,负值表示下对角线。我们已使用正值 K 设置了上对角线。
eye() 函数返回一个数组,其中所有元素都等于零,除了第 k 个对角线,其值等于 1。dtype 是返回数组的数据类型。order 指示输出是否应以行主序(C 样式)或列主序(Fortran 样式)存储在内存中。
like 参数是一个参考对象,允许创建不是 NumPy 数组的数组。如果作为 like 传入的类数组支持 __array_function__ 协议,则结果将由其定义。在这种情况下,它确保创建与通过此参数传入的类数组兼容的数组对象。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组。numpy.eye() 返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。第三个参数即 K 是对角线的索引:0(默认值)表示主对角线,正值表示上对角线,负值表示下对角线。我们已使用正值 K 设置了上对角线 -
arr = np.eye(4, k = 1)
显示数组 -
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.
# The 3rd parameter i.e. K is the Index of the diagonal: 0 (the default) refers to the main diagonal,
# a positive value refers to an upper diagonal,
# and a negative value to a lower diagonal.
# We have set the upper diagonal with a positive value K
arr = np.eye(4, k = 1)
# 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... [[0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.] [0. 0. 0. 0.]] 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