编写 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
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下