编写 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
html
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP