在NumPy中创建数组:对角线及其以下元素为1,其余元素为0


要创建一个数组,使其对角线及其以下元素为1,其余元素为0,请在Python NumPy中使用**numpy.tri()**方法。

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

tri()函数返回一个数组,其下三角形填充为1,其他地方为0;换句话说,当j <= i + k时,T[i,j] == 1,否则为0。

步骤

首先,导入所需的库。

import numpy as np

现在,使用Python NumPy中的numpy.tri()方法创建一个数组,使其对角线及其以下元素为1,其余元素为0。

arr = np.tri(4, 4)

显示我们的数组。

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)

示例

import numpy as np

# To create an array with ones at and below the given 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
arr = np.tri(4, 4)

# 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)

输出

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

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

更新于:2022年2月16日

272 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.