在 Numpy 中创建二维数组,并将扁平化的输入作为下对角线


要创建二维数组,并将扁平化的输入作为对角线,可以使用 Python Numpy 中的 **numpy.diagflat()** 方法。'K 参数用于设置对角线;0(默认值)对应于“主”对角线,负 k 表示主对角线下方第 k 条对角线。

第一个参数是输入数据,该数据被展平并设置为输出的第 k 条对角线。第二个参数是要设置的对角线;0(默认值)对应于“主”对角线,正(负)k 表示主对角线上方(下方)第 k 条对角线。

NumPy 提供了全面的数学函数、随机数生成器、线性代数例程、傅里叶变换等等。它支持各种硬件和计算平台,并且可以很好地与分布式、GPU 和稀疏数组库配合使用。

步骤

首先,导入所需的库 -

import numpy as np

使用 numpy.array() 方法创建 2D 数组 -

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() 方法创建二维数组,并将扁平化的输入作为对角线。'K 参数用于设置对角线;0(默认值)对应于“主”对角线,负 k 表示主对角线下方第 k 条对角线 -

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 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 0 0 0 0]
[ 5 0 0 0 0]
[ 0 10 0 0 0]
[ 0 0 15 0 0]
[ 0 0 0 20 0]]

更新于: 2022年2月16日

100 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.