在 Numpy 中返回数组的上三角
若要返回数组的上三角,请在 Python NumPy 中使用 **numpy.triu()** 方法。第 1 个参数是输入数组。该函数会返回一个副本,其 kth 对角线以下的元素清零。对于维度超过 2 的数组,triu 会应用于最后两个轴。
步骤
首先,导入所需的库 −
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.triu() 方法。第 1 个参数是输入数组 −
print("
Result...
",np.triu(arr))
示例
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 upper triangle of an array, use the numpy.triu() method in Python Numpy
# The 1st parameter is the input array
print("
Result...
",np.triu(arr))输出
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 78 88] [ 0 81 98 45] [ 0 0 54 69] [ 0 0 0 99]]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C ++
C#
MongoDB
MySQL
Javascript
PHP