เมธอด sort_values() ใช้เรียงลำดับแถวของ DataFrame ตามคอลัมน์ที่ระบุ รองรับการเรียงหลายคอลัมน์ ขึ้น/ลง และการจัดการ NaN
พารามิเตอร์สำคัญ
| พารามิเตอร์ | ค่าเริ่มต้น | คำอธิบาย |
|---|---|---|
by | (required) | ชื่อคอลัมน์ หรือ list ของคอลัมน์ |
axis | 0 | 0 = เรียงแถว, 1 = เรียงคอลัมน์ |
ascending | True | True = น้อยไปมาก, False = มากไปน้อย |
inplace | False | True = แก้ไข DataFrame เดิม |
na_position | 'last' | 'first' = NaN ขึ้นบน, 'last' = NaN ลงล่าง |
kind | 'quicksort' | อัลกอริทึม: 'quicksort', 'mergesort', 'heapsort', 'stable' |
ignore_index | False | True = รีเซ็ต index หลังเรียง |
ตัวอย่าง: เรียงตามคอลัมน์ Car (ข้อความ)
import pandas as pd
dataFrame = pd.read_csv(r"C:\Users\amit_\Desktop\SalesRecords.csv")
print("Original:\n", dataFrame)
# เรียงตาม Car A-Z
dataFrame.sort_values("Car", axis=0, ascending=True, inplace=True, na_position='first')
print("\nSorted by Car (A-Z):\n", dataFrame)
ตัวอย่าง: เรียงตามคอลัมน์ Reg_Price (ตัวเลข)
# เรียงตาม Reg_Price น้อยไปมาก
dataFrame.sort_values("Reg_Price", axis=0, ascending=True, inplace=True, na_position='first')
print("\nSorted by Reg_Price (ascending):\n", dataFrame)
โค้ดตัวอย่างสมบูรณ์
import pandas as pd
dataFrame = pd.read_csv(r"C:\Users\amit_\Desktop\SalesRecords.csv")
print("Input CSV:\n", dataFrame)
# เรียงตาม Car
dataFrame.sort_values("Car", axis=0, ascending=True, inplace=True, na_position='first')
print("\nSorted by Car Names:\n", dataFrame)
# เรียงตาม Reg_Price
dataFrame.sort_values("Reg_Price", axis=0, ascending=True, inplace=True, na_position='first')
print("\nSorted by Registration Price:\n", dataFrame)
ผลลัพธ์
Input CSV:
Car Date_of_Purchase Reg_Price
0 BMW 10/10/2020 1000
1 Audi 10/12/2020 750
2 Lexus 10/17/2020 1250
3 Jaguar 10/16/2020 1500
4 Mustang 10/19/2020 1100
5 Lamborghini 10/22/2020 1000
Sorted by Car Names:
Car Date_of_Purchase Reg_Price
1 Audi 10/12/2020 750
0 BMW 10/10/2020 1000
3 Jaguar 10/16/2020 1500
5 Lamborghini 10/22/2020 1000
2 Lexus 10/17/2020 1250
4 Mustang 10/19/2020 1100
Sorted by Registration Price:
Car Date_of_Purchase Reg_Price
1 Audi 10/12/2020 750
0 BMW 10/10/2020 1000
5 Lamborghini 10/22/2020 1000
4 Mustang 10/19/2020 1100
2 Lexus 10/17/2020 1250
3 Jaguar 10/16/2020 1500
เรียงหลายคอลัมน์ (Multi-column Sort)
# เรียงตาม Reg_Price ก่อน แล้วตาม Car
df.sort_values(by=['Reg_Price', 'Car'], ascending=[True, False])
# ใช้ ignore_index=True เพื่อ reset index
df.sort_values('Reg_Price', ignore_index=True)
Best Practices
- ใช้
inplace=False(default) และ assign:df = df.sort_values(...) - ใช้
ignore_index=Trueเพื่อ index ต่อเนื่องหลังเรียง kind='stable'รักษาลำดับเดิมของค่าที่เท่ากัน (stable sort)- Time-series: ตั้ง index เป็น datetime แล้ว
df.sort_index()