编写 Python 代码来交换给定数据框中的最后两行

pythonpandasserver side programmingprogramming更新于 2024/6/20 23:08:17

假设您有数据框和交换最后两行的结果,

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

相关文章


有用资源