sort_values() 是 pandas 中最常用的排序方法,
它可以按指定欄位對資料進行排序。
讓我用一個簡單的例子來解釋:
基本例子:水果價格表
import pandas as pd
# 創建簡單的水果價格表
fruits_df = pd.DataFrame({
'水果': ['蘋果', '香蕉', '橙子', '草莓', '藍莓'],
'價格': [30, 15, 25, 80, 120],
'庫存': [100, 200, 80, 50, 30]
})
print("原始資料:")
print(fruits_df)輸出:

單一欄位排序:
# 依據「價格」欄位排序
sorted_fruits = fruits_df.sort_values('價格')
print("\n依價格排序 (預設升序):")
print(sorted_fruits)輸出:

降序排序
# 依據「價格」欄位降序排序
sorted_fruits_desc = fruits_df.sort_values('價格', ascending=False)
print("\n依價格降序排序:")
print(sorted_fruits_desc)輸出:

推薦hahow線上學習python: https://igrape.net/30afN

![Python如何寫入docx文件? from docx import Document ; doc = Document() ; table = doc.add_table(rows=5, cols=3) ; table.cell(r,c).text = str(tabs[r][c]) ; doc.add_heading ; p = doc.add_paragraph ; p.add_run ; doc.add_picture ; 使用wordPad開啟會少最後一個row,可以用免費的LibreOffice Python如何寫入docx文件? from docx import Document ; doc = Document() ; table = doc.add_table(rows=5, cols=3) ; table.cell(r,c).text = str(tabs[r][c]) ; doc.add_heading ; p = doc.add_paragraph ; p.add_run ; doc.add_picture ; 使用wordPad開啟會少最後一個row,可以用免費的LibreOffice](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/09/20220914154313_30.jpg?quality=90&zoom=2&ssl=1&resize=350%2C233)








近期留言