在Numpy中创建二维数组,并将扁平化输入作为上对角线
要创建一个二维数组,并将扁平化输入作为对角线,可以使用 Python Numpy 中的 **numpy.diagflat()** 方法。“K”参数用于设置对角线;默认值为 0,对应于“主”对角线,正(负)k 值表示高于(低于)主对角线的对角线数。
第一个参数是输入数据,它会被扁平化并设置为输出的第 k 个对角线。第二个参数是要设置的对角线;默认值为 0,对应于“主”对角线,正(负)k 值表示高于(低于)主对角线的对角线数。
NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且与分布式、GPU 和稀疏数组库兼容良好。
步骤
首先,导入所需的库:
import numpy as np
使用 numpy.array() 方法创建一个二维数组:
arr = np.array([[5, 10], [15, 20]])
显示我们的数组:
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)要创建一个二维数组,并将扁平化输入作为对角线,可以使用 numpy.diagflat() 方法:
print("
Result...
",np.diagflat(arr, k = 1))
示例
import numpy as np
# Create a 2D array using the numpy.array() method
arr = np.array([[5, 10], [15, 20]])
# 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 create a two-dimensional array with the flattened input as a diagonal, use the numpy.diagflat() method in Python Numpy
# The 'K parameter is used to set the diagonal; 0, the default, corresponds to the “main” diagonal,
# a positive (negative) k giving the number of the diagonal above (below) the main.
print("
Result...
",np.diagflat(arr, k = 1))输出
Array... [[ 5 10] [15 20]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (2, 2) Elements in the Array... 4 Result... [[ 0 5 0 0 0] [ 0 0 10 0 0] [ 0 0 0 15 0] [ 0 0 0 0 20] [ 0 0 0 0 0]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP