创建一个连续的扁平 NumPy 数组
让我们看看如何在 NumPy 中创建一个连续数组。连续展平数组是一个二维和多维数组,存储为一维数组。我们将使用 ravel() 方法来执行此任务。
Syntax : numpy.ravel(array, order = ‘C’)
Parameters :
- array : Input array.
- order : C-contiguous, F-contiguous, A-contiguous; optional
Returns : Flattened array having same type as the Input array and and order as per choice.
示例 1:展平二维数组。
Python3
# Importing libraries
import numpy as np
# Creating 2D array
arr = np.array([[5, 6, 7], [8, 9, 10]])
print("Original array:\n", arr)
# Flattening the array
flattened_array = np.ravel(arr)
print("New flattened array:\n", flattened_array)
Python3
# Importing libraries
import numpy as np
# Creating 3D array
arr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])
print("Original array:\n", arr)
# Flattening the array
flattened_array = np.ravel(arr)
print("New flattened array:\n", flattened_array)
输出 :
Original array:
[[ 5 6 7]
[ 8 9 10]]
New flattened array:
[ 5 6 7 8 9 10]
示例 2:展平 3D 阵列。
Python3
# Importing libraries
import numpy as np
# Creating 3D array
arr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])
print("Original array:\n", arr)
# Flattening the array
flattened_array = np.ravel(arr)
print("New flattened array:\n", flattened_array)
输出 :
Original array:
[[[3 4]
[5 6]]
[[7 8]
[9 0]]]
New flattened array:
[3 4 5 6 7 8 9 0]
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。