Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโค้ด Python สลับ 2 แถวสุดท้ายใน DataFrame

สมมติว่าคุณมี DataFrame และต้องการสลับตำแหน่งของ 2 แถวสุดท้าย

วิธีแก้ปัญหา

  1. สร้าง DataFrame
  2. เก็บแถวสุดท้ายไว้ในตัวแปร temp
  3. กำหนดแถวสุดท้าย = แถวที่สองจากท้าย
  4. กำหนดแถวที่สองจากท้าย = 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("ก่อนสลับ:\n", df)

# สลับ 2 แถวสุดท้าย
temp = df.iloc[-1].copy()  # ใช้ copy() ป้องกัน reference issue
df.iloc[-1] = df.iloc[-2]
df.iloc[-2] = temp

print("\nหลังสลับ:")
print(df)

ผลลัพธ์

ก่อนสลับ:
    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

หลังสลับ:
    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

คำอธิบาย:

  • iloc[-1] อ้างถึงแถวสุดท้าย, iloc[-2] อ้างถึงแถวที่สองจากท้าย
  • ต้องใช้ .copy() เมื่อเก็บค่าไว้ใน temp ไม่งั้นจะเป็น reference ชี้ไปที่ข้อมูลเดิม ทำให้สลับผิดพลาด
  • วิธีนี้แก้ไข DataFrame เดิม (in-place)