編寫 Python 程式碼以交換給定資料框中的最後兩行
假設你有一個數據框和要交換的最後兩行的結果,
Before swapping Name Age Maths Science English 0 David 13 98 75 79 1 Adam 12 59 96 45 2 Bob 12 66 55 70 3 Alex 13 95 49 60 4 Serina 12 70 78 80 After swapping Name Age Maths Science English 0 David 13 98 75 79 1 Adam 12 59 96 45 2 Bob 12 66 55 70 3 Serina 12 70 78 80 4 Alex 13 95 49 60
解決方案
為了解決這個問題,我們將按照下面給定的方法進行操作-
定義一個數據框
建立臨時資料以儲存最後一行。它定義如下,
temp = df.iloc[-1]
將第二行值交換到第一行,並將臨時資料分配給第二行。它定義如下,
df.iloc[-1] = df.iloc[-2] df.iloc[-2] = temp
示例
讓我們看看下面的實現以獲得更好的理解 -
import pandas as pd data = {'Name': ['David', 'Adam', 'Bob', 'Alex', 'Serina'], 'Age' : [13,12,12,13,12], 'Maths': [98, 59, 66, 95, 70], 'Science': [75, 96, 55, 49, 78], 'English': [79, 45, 70, 60, 80]} df = pd.DataFrame(data) print("Before swapping\n",df) temp = df.iloc[-1] df.iloc[-1] = df.iloc[-2] df.iloc[-2] = temp print("After swapping\n",df)
輸出
Before swapping Name Age Maths Science English 0 David 13 98 75 79 1 Adam 12 59 96 45 2 Bob 12 66 55 70 3 Alex 13 95 49 60 4 Serina 12 70 78 80 After swapping Name Age Maths Science English 0 David 13 98 75 79 1 Adam 12 59 96 45 2 Bob 12 66 55 70 3 Serina 12 70 78 80 4 Alex 13 95 49 60
廣告