编写 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