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 表達式中的魔法:用海象運算子讓斷詞程式碼更乾淨 [w_clean for w in words if (w_clean:=w.lower().strip()) and w_clean not in STOPWORDS] Python 表達式中的魔法:用海象運算子讓斷詞程式碼更乾淨 [w_clean for w in words if (w_clean:=w.lower().strip()) and w_clean not in STOPWORDS]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2026/02/20260210083748_0_a7d9bf.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python: 如何判斷字符串內容是否為數字(整數或浮點數)? isinstance( eval( entry.get() ), (float, int) ) ; str.isdigit() #不包括小數點和負號 ; try~ except ValueError~ ; 正則表示法 regular expression ; pattern = ‘^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$’ Python: 如何判斷字符串內容是否為數字(整數或浮點數)? isinstance( eval( entry.get() ), (float, int) ) ; str.isdigit() #不包括小數點和負號 ; try~ except ValueError~ ; 正則表示法 regular expression ; pattern = ‘^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$’](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2023/05/20230512152430_3.png?quality=90&zoom=2&ssl=1&resize=350%2C233)






近期留言