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

Python - ย้ายคอลัมน์ไปตำแหน่งแรกใน Pandas DataFrame

ใช้ pop() ดึงคอลัมน์ออกมา แล้ว insert(0, col_name, data) ใส่กลับที่ตำแหน่ง 0 (First Position)

ตัวอย่างโค้ด

import pandas as pd

dataFrame = pd.DataFrame({
    "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'],
    "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'],
    "Roll Number": [5, 10, 3, 8, 2, 9, 6]
})

print("DataFrame ...\n", dataFrame)

# Move "Roll Number" to first position
shiftPos = dataFrame.pop("Roll Number")
dataFrame.insert(0, "Roll Number", shiftPos)

print("\nUpdated DataFrame after moving a column to the first position...\n", dataFrame)

ผลลัพธ์

Updated DataFrame after moving a column to the first position...
   Roll Number Result   Student
0            5   Pass     Jack
1           10   Fail    Robin
2            3   Pass      Ted
3            8   Fail     Marc
4            2   Pass  Scarlett
5            9   Pass      Kat
6            6   Pass     John

คำอธิบาย

  • pop("col") ลบคอลัมน์และคืนค่า Series
  • insert(loc, column, value) แทรกคอลัมน์ที่ตำแหน่ง loc (0 = First)
  • วิธีนี้แก้ไข DataFrame เดิม (In-place)
  • วิธีอื่น: df = df[['Roll Number', 'Student', 'Result']] (Reorder by list)