Method:
np.triu(m, k=0)
Extracts the upper triangular part of an array.
Returns:
np.ndarray
Parameters:
m: array-like-
The input matrix.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.triu(m=matrix, k=0)
print(result)
'''
Output:
[[1 2 3]
[0 5 6]
[0 0 9]]
'''
k: int, Optional-
The diagonal offset (default 0). A positive value refers to an upper diagonal, and a negative value to a lower diagonal.
k = 0 (default) +
The diagonal offset is 0,0.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.triu(m=matrix, k=0)
print(result)
'''
Output:
[[1 2 3]
[0 5 6]
[0 0 9]]
'''
k = 1 +
The diagonal offset is 0,1.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.triu(m=matrix, k=1)
print(result)
'''
Output:
[[0 2 3]
[0 0 6]
[0 0 0]]
'''
k = -1 +
The diagonal offset is 1,0.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
result = np.triu(m=matrix, k=-1)
print(result)
'''
Output:
[[1 2 3]
[4 5 6]
[0 8 9]]
'''