Python 中的 numpy.triu 方法
numpy.triu() 方法可用于获取数组的上三角。它的语法如下 −
语法
numpy.triu(m, k=0)
其中,
m - 数组中的行数。
k - 这是对角线。对主对角线使用 k=0。k < 0 在主对角线下方,k > 0 在主对角线上方。
它返回一个数组的副本,将 kth 对角线以上的所有元素替换为零。
示例 1
考虑以下示例 −
# import numpy library
import numpy as np
# create an input matrix
x = np.matrix([[6, 7], [8, 9], [10, 11]])
print("Input of Matrix :
", x)
# numpy.triu() function
y = np.triu(x, 1)
# Display Triu Values
print("Triu Elements:
", y)输出
将生成以下输出 −
Input of Matrix : [[ 6 7] [ 8 9] [10 11]] Triu Elements: [[0 7] [0 0] [0 0]]
示例 2
我们再举一个例子 −
# import numpy library
import numpy as np
# create an input matrix
a = np.matrix([[11, 12, 13], [20, 21, 22], [44, 45, 46]])
print("Input of Matrix :
", a)
# numpy.triu() function
b = np.triu(a, -1)
# Display Triu Values
print("Triu Elements:
", b)输出
将生成以下输出 −
Input of Matrix : [[11 12 13] [20 21 22] [44 45 46]] Triu Elements: [[11 12 13] [20 21 22] [ 0 45 46]]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP