บทนำ
ใช้เมธอด sort_values() ของ DataFrame จัดเรียงตามหลายคอลัมน์ หากคอลัมน์แรกมีค่าซ้ำ จะใช้คอลัมน์ที่สองตัดสิน
ขั้นตอน
- อ่านไฟล์
SalesRecords.csv - เรียงตาม
Reg_PriceและCarพร้อมกัน:dataFrame.sort_values(["Reg_Price", "Car"], axis=0, ascending=True, inplace=True, na_position='first')
โค้ดเต็ม
import pandas as pd
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesRecords.csv")
print("\nInput CSV file = \n", dataFrame)
# เรียงตามหลายคอลัมน์
dataFrame.sort_values(["Reg_Price", "Car"], axis=0,
ascending=True, inplace=True, na_position='first')
print("\nSorted CSV file (according to multiple columns) = \n", dataFrame)
ผลลัพธ์
ข้อมูลเรียงตาม Reg_Price น้อยไปมาก หากราคาเท่ากัน เรียงตามชื่อรถ A-Z