在Numpy中创建主对角线上方为1,其他位置为0的数组


要创建一个主对角线上方为1,其他位置为0的数组,可以使用Python Numpy中的**numpy.tri()**方法。

  • 第一个参数是数组的行数。

  • 第二个参数是数组的列数。

  • 第三个参数'k'是填充数组的子对角线及其下方的位置。

k = 0为主对角线,k < 0在其下方,k > 0在其上方。默认值为0。tri()函数返回一个数组,其下三角形填充为1,其他位置为0;换句话说,当j <= i + k时,T[i,j] == 1,否则为0。

步骤

首先,导入所需的库:

import numpy as np

现在,创建一个主对角线上方为1,其他位置为0的数组,使用numpy.tri()方法:

arr = np.tri(4, 4, k = 1)

显示数组:

print("Array...
",arr)

获取数据类型:

print("
Array datatype...
",arr.dtype)

获取数组的维度:

print("
Array Dimensions...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

获取数组的元素个数:

print("
Elements in the Array...
",arr.size)

示例

Open Compiler
import numpy as np # To create an array with ones above the main diagonal and zeros elsewhere, use the numpy.tri() method in Python Numpy # The 1st parameter is the number of rows in the array # The 2nd parameter is the number of columns in the array # The 3rd parameter 'k' is the sub-diagonal at and below which the array is filled. # The k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0. arr = np.tri(4, 4, k = 1) # Displaying our array print("Array...",arr) # Get the datatype print("Array datatype...",arr.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr.ndim) # Get the shape of the Array print("Our Array Shape...",arr.shape) # Get the number of elements of the Array print("Elements in the Array...",arr.size)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Array...
[[1. 1. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

更新于:2022年2月10日

617 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告