在NumPy中使用不同输出类型创建在给定对角线及其以下位置为1,其他位置为0的数组


要创建一个在给定对角线及其以下位置为1,其他位置为0的数组,请在Python NumPy中使用**numpy.tri()**方法。

  • 第一个参数是数组的行数。
  • 第二个参数是数组的列数。
  • "type"参数用于设置返回数组的类型。

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

步骤

首先,导入所需的库:

import numpy as np

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

arr = np.tri(3, 5, dtype = int)

显示我们的数组:

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
# The "type" parameter is used to set the type of the returned array
arr = np.tri(3, 5, dtype = int)

# 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 0]
[1 1 0 0 0]
[1 1 1 0 0]]

Array datatype...
int64

Array Dimensions...
2

Our Array Shape...
(3, 5)

Elements in the Array...
15

更新于:2022年2月16日

78 次浏览

开启您的职业生涯

完成课程获得认证

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