返回一个对角线为1,其他位置为0的二维数组,并设置NumPy中的列数
numpy.eye() 函数返回一个二维数组,对角线元素为 1,其他元素为 0。第一个参数表示输出数组的行数,例如,4 表示 4x4 数组。第二个参数表示输出数组的列数。
eye() 函数返回一个数组,其中所有元素都等于零,除了第 k 个对角线上的元素等于一。dtype 是返回数组的数据类型。order 指定输出是否应以行主序 (C 样式) 或列主序 (Fortran 样式) 存储在内存中。
like 参数是一个参考对象,允许创建非 NumPy 数组的数组。如果作为 like 传入的类数组支持 __array_function__ 协议,则结果将由其定义。在这种情况下,它确保创建与通过此参数传入的数组对象兼容的数组对象。
步骤
首先,导入所需的库:
import numpy as np
创建一个二维数组。numpy.eye() 返回一个二维数组,对角线元素为 1,其他元素为 0。第一个参数表示输出数组的行数,例如,4 表示 4x4 数组。第二个参数表示输出数组的列数。这里我们设置为 3:
arr = np.eye(4, 3)
显示数组:
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. We have set 3 here
arr = np.eye(4, 3)
# 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. 1. 0.] [0. 0. 1.] [0. 0. 0.]] Array type... float64 Array shape... (4, 3) Array Dimensions... 2 Array (count of elements)... 12
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP