NumPy 反轉陣列

Muhammad Maisam Abbas 2023年1月30日 NumPy
  1. 使用 Python 中的基本切片方法反轉 NumPy 陣列
  2. 在 Python 中使用 numpy.flipud() 函式反轉 NumPy 陣列
  3. 在 Python 中使用 numpy.flip() 函式反轉 NumPy 陣列
NumPy 反轉陣列

本教程將介紹在 Python 中反轉 NumPy 陣列的方法。

使用 Python 中的基本切片方法反轉 NumPy 陣列

我們可以使用基本的切片方法來反轉 NumPy 陣列。我們可以使用 [::-1] 作為陣列的索引來反轉它。此方法實際上並不反轉原始陣列。相反,它將建立一個陣列的自定義檢視,該檢視指向原始陣列,但順序相反。以下程式碼示例演示瞭如何使用 Python 中的基本切片方法來反轉 NumPy 陣列。

import numpy as np

array = np.array([1, 2, 3, 4, 5])
reverse = array[::-1]
print(reverse)

輸出:

[5 4 3 2 1]

在上面的程式碼中,我們在 Python 中使用 array[::-1] 索引反轉了 NumPy 陣列 array 的元素。我們首先建立並初始化陣列 array,然後使用基本切片方法將 array 的反向檢視儲存在 reverse 陣列中。最後,我們使用 Python 中的 print() 函式在 reverse 陣列中顯示值。

在 Python 中使用 numpy.flipud() 函式反轉 NumPy 陣列

可以用來反轉陣列的另一個函式是 numpy.flipud() 函式。numpy.flipud() 函式將陣列的元素上下顛倒。numpy.flipud() 函式將陣列作為引數,並返回該陣列的相反值。請參見以下程式碼示例。

import numpy as np

array = np.array([1, 2, 3, 4, 5])
reverse = np.flipud(array)
print(reverse)

輸出:

[5 4 3 2 1]

在上面的程式碼中,我們使用 python 中的 numpy.flipud() 函式反轉了 NumPy 陣列 array 元素。我們首先使用 numpy.array() 函式建立並初始化了原始陣列 array。然後,我們使用 numpy.flipud() 函式反轉 array 並將結果儲存在 reverse 陣列中。

在 Python 中使用 numpy.flip() 函式反轉 NumPy 陣列

我們還可以使用 numpy.flip() 函式在 Python 中反轉 NumPy 陣列。numpy.flip() 函式沿 Python 中指定的 axis 反轉陣列中元素的順序。預設情況下,axis 的值設定為 None。我們不需要為一維 NumPy 陣列指定軸。請參見以下程式碼示例。

import numpy as np

array = np.array([1, 2, 3, 4, 5])
reverse = np.flip(array)
print(reverse)

輸出:

[5 4 3 2 1]

在上面的程式碼中,我們使用 Python 中的 numpy.flip() 函式反轉了 NumPy 陣列 array 元素。我們首先使用 numpy.array() 函式建立並初始化了原始陣列 array。然後,使用 numpy.flip() 函式反轉 array 內元素的順序,並將結果儲存在 reverse 陣列內。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn