如何获得 3D NumPy 数组的所有 2D 对角线?
让我们看看获取 3D NumPy 数组的所有 2D 对角线的程序。因此,为此我们使用 NumPy 库的numpy.diagonal()函数。此函数从 n 维数组返回指定的对角线。
Syntax: numpy.diagonal(a, axis1, axis2)
Parameters:
- a: represents array from which diagonals has to be taken
- axis1: represents first axis to be taken for 2-d subarray
- axis2: represents second axis to be taken for 2-d subarray
Return: array of diagonal elements.
现在,让我们看一个例子:
示例 1:
Python3
# Import the numpy package
import numpy as np
# Create 3D-numpy array
# of 4 rows and 4 columns
arr = np.arange(3 * 4 * 4).reshape(3, 4, 4)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print("2d diagonal array:\n",
diag_arr)
Python3
# Import the numpy package
import numpy as np
# Create 3D numpy array
# of 3 rows and 4 columns
arr = np.arange(3 * 3 * 4).reshape(3, 3, 4)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print("2d diagonal array:\n",
diag_arr)
Python3
# Import the numpy package
import numpy as np
# Create 3D numpy array
# of 5 rows and 6 columns
arr = np.arange(3 * 5 * 6).reshape(3, 5, 6)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print("2d diagonal array:\n",
diag_arr)
输出:
Original 3d array:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]]
2d diagonal array:
[[ 0 5 10 15]
[16 21 26 31]
[32 37 42 47]]
示例 2:
Python3
# Import the numpy package
import numpy as np
# Create 3D numpy array
# of 3 rows and 4 columns
arr = np.arange(3 * 3 * 4).reshape(3, 3, 4)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print("2d diagonal array:\n",
diag_arr)
输出:
Original 3d array:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
[[24 25 26 27]
[28 29 30 31]
[32 33 34 35]]]
2d diagonal array:
[[ 0 5 10]
[12 17 22]
[24 29 34]]
示例 3:
Python3
# Import the numpy package
import numpy as np
# Create 3D numpy array
# of 5 rows and 6 columns
arr = np.arange(3 * 5 * 6).reshape(3, 5, 6)
print("Original 3d array:\n",
arr)
# Create 2D diagonal array
diag_arr = np.diagonal(arr,
axis1 = 1,
axis2 = 2)
print("2d diagonal array:\n",
diag_arr)
输出:
Original 3d array:
[[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]]
[[30 31 32 33 34 35]
[36 37 38 39 40 41]
[42 43 44 45 46 47]
[48 49 50 51 52 53]
[54 55 56 57 58 59]]
[[60 61 62 63 64 65]
[66 67 68 69 70 71]
[72 73 74 75 76 77]
[78 79 80 81 82 83]
[84 85 86 87 88 89]]]
2d diagonal array:
[[ 0 7 14 21 28]
[30 37 44 51 58]
[60 67 74 81 88]]