NumPy reshape() 函式



NumPy 的reshape()函式用於更改陣列的形狀而不改變其資料。它返回一個具有指定維度的新檢視或陣列,前提是元素總數保持不變。

此函式有兩個主要引數:一個是要重塑的陣列,另一個是指定新形狀的元組。如果新形狀與元素總數不相容,則會引發“ValueError”。

NumPy 的reshape()函式對於將資料轉換為適合不同處理要求的格式非常有用,例如在行主序和列主序格式之間轉換,或為機器學習模型準備資料。

語法

NumPy reshape()函式的語法如下:

numpy.reshape(arr, newshape, order='C')

引數

以下是 NumPy reshape() 函式的引數:

  • arr: 要重塑的輸入陣列。
  • newshape: 此引數可以是整數或整數元組。新形狀應與原始形狀相容。
  • order: 此引數定義讀寫順序。如果為 'C' 則為行主序,'F' 則為列主序。

返回值

reshape() 函式返回一個具有相同資料但不同形狀的新陣列。

示例 1

以下是 NumPy reshape() 函式的基本示例。在這個例子中,我們將一個包含 8 個元素的一維陣列重塑為一個 2x4 的二維陣列:

import numpy as np

# Create a 1D array with 8 elements
a = np.arange(8)
print('The original array:')
print(a)
print('\n')

# Reshape the array to a 2D array with shape (4, 2)
b = a.reshape(4, 2)
print('The modified array:')
print(b)

輸出

The original array:
[0 1 2 3 4 5 6 7]


The modified array:
[[0 1]
 [2 3]
 [4 5]
 [6 7]]

示例 2

此示例使用 -1 自動計算將 2x3 陣列重塑為 3x2 陣列的適當維度:

import numpy as np

# Original array
a = np.array([[1, 2, 3], [4, 5, 6]])
# Reshaping the array to 3x2 using -1 to infer one of the dimensions
reshaped_array = np.reshape(a, (3, -1))

print("Original array:")
print(a)
print("Reshaped array (3x2):")
print(reshaped_array)

輸出

Original array:
[[1 2 3]
 [4 5 6]]
Reshaped array (3x2):
[[1 2]
 [3 4]
 [5 6]]

示例 3

眾所周知,我們可以根據需要分配 order 引數,因此,在下面的示例中,我們透過將 order 定義為 'F'(即 Fortran 式列主序)來將 2x3 陣列重塑為 3x2 陣列:

import numpy as np

# Original array
a = np.array([[1, 2, 3], [4, 5, 6]])
# Reshaping the array to 3x2 in Fortran-like order
reshaped_array = np.reshape(a, (3, 2), order='F')

print("Original array:")
print(a)
print("Reshaped array (3x2) in Fortran-like order:")
print(reshaped_array)

輸出

Original array:
[[1 2 3]
 [4 5 6]]
Reshaped array (3x2) in Fortran-like order:
[[1 5]
 [4 3]
 [2 6]]
numpy_array_manipulation.htm
廣告