返回一个对角线为1,其他位置为0的二维数组,但在Numpy中设置不同的数据类型
**numpy.eye()** 函数返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。这里,第一个参数表示“输出的行数”,例如 4 表示 4x4 数组。第二个参数是输出的列数。如果为 None,则默认为第一个参数,这里为 4x4。**dtype** 参数用于设置返回数组的不同数据类型。
eye() 函数返回一个数组,其中所有元素都等于零,除了第 k 个对角线上的元素,其值为 1。dtype 是返回数组的数据类型。order 指定输出是否应以行主序(C 样式)或列主序(Fortran 样式)存储在内存中。
like 参数是一个引用对象,允许创建不是 NumPy 数组的数组。如果作为 like 传入的类数组支持 __array_function__ 协议,则结果将由它定义。在这种情况下,它确保创建与通过此参数传入的类数组兼容的数组对象。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组。numpy.eye() 返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0。这里,第一个参数表示“输出的行数”,例如 4 表示 4x4 数组。第二个参数是输出的列数。如果为 None,则默认为第一个参数,这里为 4x4。**dtype** 参数用于设置返回数组的不同数据类型 -
arr = np.eye(4, dtype = float)
显示数组 -
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.
# The "dtype" parameter is used to set a different datatype of the returned array
arr = np.eye(4, dtype = float)
# 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