返回数组的下三角,并在 NumPy 中将对角线以上元素设置为零
要返回数组的下三角,请在 Python NumPy 中使用 **numpy.tril()** 方法 -
- 第一个参数是输入数组
- 第二个参数是“k”,即要将元素归零的对角线以上。
- k = 0(默认值)为主对角线,k < 0 在其下方,k > 0 在其上方。
该函数返回一个数组的副本,其中 k 对角线以上的元素归零。对于 ndim 超过 2 的数组,tril 将应用于最后两个轴。
步骤
首先,导入所需的库 -
import numpy as np
创建一个二维数组 -
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69 ], [69, 80, 80, 99]])
显示我们的数组 -
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)使用 Python NumPy 中的 numpy.tril() 方法返回数组的下三角。第二个参数是“k”,即要将元素归零的对角线以上。这里,k = 0(默认值)为主对角线,k < 0 在其下方,k > 0 在其上方 -
print("
Result...
",np.tril(arr, k = 1))
示例
import numpy as np
# Create a 2d array
arr = np.array([[36, 36, 78, 88], [92, 81, 98, 45], [22, 67, 54, 69], [69, 80, 80, 99]])
# 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)
# To return the lower triangle of an array, use the numpy.tril() method in Python Numpy
# The 1st parameter is the input array
# The 2nd parameter is the 'k' i.e. the diagonal above which to zero elements.
# k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.' array
print("
Result...
",np.tril(arr, k = 1))输出
Array... [[36 36 78 88] [92 81 98 45] [22 67 54 69] [69 80 80 99]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (4, 4) Elements in the Array... 16 Result... [[36 36 0 0] [92 81 98 0] [22 67 54 69] [69 80 80 99]]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP