獲取 Pandas DataFrame 的最後 n 條記錄


資料分析經常面臨處理海量資料集的問題,這通常需要對資料進行修改以獲得有價值的見解。在某些情況下,能夠從 Pandas DataFrame 中提取最新的 n 個條目可能很有用。本文旨在提供一個完整的操作指南,以成功完成此操作。

安裝和語法

pip install pandas

安裝 Pandas 後,您可以使用 CSV 檔案或資料庫查詢的結果從各種資料來源建立 DataFrame。

import pandas as pd
data = {'Name': ['John', 'Mark', 'Alice', 'Julie', 'Lisa', 'David'],
        'Age': [23, 34, 45, 19, 28, 31],
        'Gender': ['M', 'M', 'F', 'F', 'F', 'M']}
df = pd.DataFrame(data)

演算法

Pandas DataFrame 的 tail() 函式檢索 DataFrame 的最後 n 行,可用於獲取 DataFrame 的最後 n 個條目。完成此任務所使用的演算法包括以下步驟

  • 可以使用 shape 引數確定 DataFrame 中的行數。

  • 要獲取 DataFrame 的最後 n 行,請使用 tail() 函式。

  • 您可以選擇將生成的 DataFrame 的索引設定為 0。

示例

現在讓我們來看一個示例,演示如何檢索 DataFrame 的最後 3 條記錄。我們將使用上一節中建立的 DataFrame。

import pandas as pd

data = {'Name': ['John', 'Mark', 'Alice', 'Julie', 'Lisa', 'David'],
        'Age': [23, 34, 45, 19, 28, 31],
        'Gender': ['M', 'M', 'F', 'F', 'F', 'M']}

df = pd.DataFrame(data)

last_3_records = df.tail(3)
print(last_3_records)

輸出

    Name  Age Gender
3  Julie   19      F
4   Lisa   28      F
5  David   31      M

生成的 last_3_records DataFrame 將包含 df DataFrame 的最後三行。或者,我們可以使用 reset_index() 函式將生成的 DataFrame 的索引重置為從 0 開始。

last_3_records = last_3_records.reset_index(drop=True)

生成的 last_3_records DataFrame 的索引將從 0 開始。

    Name  Age Gender
0  Julie   19      F
1   Lisa   28      F
2  David   31      M

應用場景

檢索 Pandas DataFrame 的最後 n 條記錄在各種場景中都很有用,例如

  • 分析大型資料集中最新的資料條目。

  • 測試和驗證資料插入 DataFrame。

  • 使用最近的資料條目構建機器學習模型。

結論

總之,檢索 Pandas DataFrame 的最後 n 條記錄是一項簡單而高效的任務,可以使用 tail() 函式完成。我們可以選擇將生成的 DataFrame 的索引重置為從 0 開始。此技術在各種場景中都很有用,例如分析最近的資料條目或驗證資料插入 DataFrame。

更新於: 2023年7月18日

2K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.