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如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content Python如何串接OpenAI /Claude /Gemini API自動將大量維修紀錄JSON轉自然語言描述(並避免中斷資料遺失)response = client.chat.completions.create() ; reply = response.choices[0].message.content](https://i1.wp.com/savingking.com.tw/wp-content/uploads/2025/07/20250716084059_0_c5b368.png?quality=90&zoom=2&ssl=1&resize=350%2C233)









近期留言