NumPy expand_dims() 函式



NumPy 的expand_dims()函式用於向陣列新增新的軸或維度。此函式接收一個輸入陣列和一個軸引數,該引數指定在何處插入新維度。

此函式的結果是一個添加了指定軸的新陣列,這對於調整陣列形狀以滿足某些運算或函式的要求非常有用。

例如,擴充套件維度通常用於透過使其與廣播或矩陣運算相容來將一維陣列轉換為二維陣列。

語法

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

numpy.expand_dims(a, axis)

引數

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

  • a : 輸入陣列。
  • axis (int): 這是在擴充套件軸中放置新軸的位置。如果我們提供一個負整數,它將從最後一個軸到第一個軸進行計數。

返回值

此函式返回維度增加一的陣列檢視。

示例 1

以下是 NumPy expand_dims() 函式的基本示例,它透過將其轉換為形狀為 (1, 3) 的二維陣列,在 1D 陣列的開頭新增一個新軸:

import numpy as np

# Original 1D array
arr = np.array([1, 2, 3])

# Expand dimensions
expanded_arr = np.expand_dims(arr, axis=0)

print("Original array:")
print(arr)
print("Shape:", arr.shape)

print("\nExpanded array:")
print(expanded_arr)
print("Shape:")
print(expanded_arr.shape)

輸出

Original array:
[1 2 3]
Shape: (3,)

Expanded array:
[[1 2 3]]
Shape: 
(1, 3)

示例 2

此示例透過將其形狀從 (2, 2, 2) 更改為 (2, 2, 2, 1),在 3D 陣列的末尾新增一個新軸:

import numpy as np

# Original 3D array
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

# Expand dimensions
expanded_arr = np.expand_dims(arr, axis=-1)

print("Original array:")
print(arr)
print("Shape:", arr.shape)

print("\nExpanded array:")
print(expanded_arr)
print("Shape:")
print(expanded_arr.shape)

執行上述程式碼後,我們將得到以下結果:

Original array:
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
Shape: 
(2, 2, 2)

Expanded array:
[[[[1]
   [2]]

  [[3]
   [4]]]


 [[[5]
   [6]]

  [[7]
   [8]]]]
Shape: (2, 2, 2, 1)

示例 3

以下示例顯示瞭如何使用expand_dims()函式透過根據需要調整其形狀和維度來向陣列新增新維度:

import numpy as np 

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

print('Array x:')
print(x)
print('\n')

# Add a new axis at position 0
y = np.expand_dims(x, axis=0)

print('Array y with a new axis added at position 0:')
print(y)
print('\n')

# Print the shapes of x and y
print('The shape of x and y arrays:')
print(x.shape, y.shape)
print('\n')

# Add a new axis at position 1
y = np.expand_dims(x, axis=1)

print('Array y after inserting axis at position 1:')
print(y)
print('\n')

# Print the number of dimensions (ndim) for x and y
print('x.ndim and y.ndim:')
print(x.ndim, y.ndim)
print('\n')

# Print the shapes of x and y
print('x.shape and y.shape:')
print(x.shape, y.shape)

執行上述程式碼後,我們將得到以下結果:

Array x:
[[1 2]
 [3 4]]


Array y with a new axis added at position 0:
[[[1 2]
  [3 4]]]


The shape of x and y arrays:
(2, 2) (1, 2, 2)


Array y after inserting axis at position 1:
[[[1 2]]

 [[3 4]]]


x.ndim and y.ndim:
2 3


x.shape and y.shape:
(2, 2) (2, 1, 2)
numpy_array_manipulation.htm
廣告