NumPy resize() 函式



Numpy 的resize()函式返回一個具有指定形狀的新陣列,並調整輸入陣列的大小。reshape()函式要求元素總數保持不變,而resize()可以透過截斷或填充陣列來更改元素總數。

如果新形狀大於原始形狀,則陣列將用原始資料的重複副本填充。如果新形狀較小,則陣列將被截斷。

此函式以輸入陣列和新形狀作為引數,並可以選擇一個refcheck引數來控制是否檢查對原始陣列的引用。

語法

以下是 Numpy resize() 函式的語法:

numpy.resize(arr, shape)

引數

以下是 Numpy resize() 函式的引數:

  • arr: 要調整大小的輸入陣列。
  • shape: 結果陣列的新形狀。
  • shape: 結果陣列的新形狀。

示例 1

以下是 Numpy resize() 函式的示例,它展示瞭如何重塑一個二維陣列,透過截斷或重複元素以適應新的指定維度:

import numpy as np

# Create a 2D array
a = np.array([[1, 2, 3], [4, 5, 6]])

print('First array:')
print(a)
print('\n')

print('The shape of the first array:')
print(a.shape)
print('\n')

# Resize the array to shape (3, 2)
b = np.resize(a, (3, 2))

print('Second array:')
print(b)
print('\n')

print('The shape of the second array:')
print(b.shape)
print('\n')

# Resize the array to shape (3, 3)
# Note: This will repeat elements of 'a' to fill the new shape
print('Resize the second array:')
b = np.resize(a, (3, 3))
print(b)

以上程式將產生以下輸出:

First array:
[[1 2 3]
 [4 5 6]]

The shape of first array:
(2, 3)

Second array:
[[1 2]
 [3 4]
 [5 6]]

The shape of second array:
(3, 2)

Resize the second array:
[[1 2 3]
 [4 5 6]
 [1 2 3]]

示例 2

以下是另一個將大小為 4x3 的給定陣列調整為 6x2 和 3x4 的示例:

import numpy as np

# Create an initial 4x3 array
array = np.array([[1, 2, 3], [4, 5, 6],[7,8,9],[10,11,12]])

print("Original array:")
print(array)
print("\n")

# Resize the array to shape (6, 2)
resized_array = np.resize(array, (6, 2))

print("Resized array to shape (6, 2):")
print(resized_array)
print("\n")

# Resize the array to shape (3, 4)
resized_array_larger = np.resize(array, (3, 4))

print("Resized array to shape (3, 4) with repeated elements:")
print(resized_array_larger)

以上程式將產生以下輸出:

Original array:
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]


Resized array to shape (6, 2):
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]]


Resized array to shape (3, 4) with repeated elements:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
numpy_array_manipulation.htm
廣告