Python - 基礎練習篇 (def)

2026-06-15

今天我們來利用 python 資料整理中一個有趣的功能 def,def 可以幫助我們定義一個簡單的邏輯計算,讓我們能夠方便的計算不同的指標,例如:BMI, 腰臀比, 腰圍等等。以下讓我們來看一下範例吧!

  1. 使用到的工具:
  • def
  • return
  • if-elif-else
  • import pandas as pd
  • pd.DataFrame()
  • df[‘’New_col]=
  • round()
  • .apply()
  • axis=1
  • lambda x:
  • and
  1. 程式碼範例:
#載入 Python 資料分析套件
import pandas as pd
 
#定義 bmi 計算分類 / return 回傳值 / if-elif-else 條件分類
def get_bmi_category(bmi):
    """將 BMI 轉為分類標籤"""
    if bmi < 18.5: return "⚖️ 體重過輕"
    elif bmi < 24: return "✅ 正常範圍"
    elif bmi < 27: return "⚠️ 過重"
    else: return "❌ 肥胖"
    
#定義 體脂肪 計算分類 / return 回傳值 / if-elif-else 條件分類
def get_fat_category(sex, fat_pct):
    """根據性別與體脂率判斷區間"""
    if sex == 'M':
        if fat_pct < 14: return "⚖️ 偏低"
        elif fat_pct <= 24: return "✅ 正常"
        else: return "⚠️ 偏高"
    else: # Female
        if fat_pct < 21: return "⚖️ 偏低"
        elif fat_pct <= 31: return "✅ 正常"
        else: return "⚠️ 偏高"
 
# 模擬資料 - 建立資料框
patients = pd.DataFrame({
    'Name': ['Alex', 'Bella', 'Chris', 'Daisy'],
    'Sex': ['M', 'F', 'M', 'F'],
    'Weight_kg': [80, 50, 75, 60],
    'Height_m': [1.75, 1.60, 1.70, 1.65],
    'BodyFat_Pct': [18, 32, 26, 22]
})
 
# 1. 計算 BMI - round(1) 數值四捨五入
patients['BMI'] = (patients['Weight_kg'] / (patients['Height_m'] ** 2)).round(1)
 
# 2. 套用分類邏輯 - df['New_Col'] 向量化衍生欄位 
# .apply() 應用函數 (Map Function) 將自訂的函式逐行(Row)或逐欄(Column)套用到整個 DataFrame 中。
# 匿名函數 (Anonymous Function) 一種不需要使用 def 命名、只有單行表達式的輕量級臨時函數。
patients['BMI_Status'] = patients['BMI'].apply(get_bmi_category)
patients['Fat_Status'] = patients.apply(lambda x: get_fat_category(x['Sex'], x['BodyFat_Pct']), axis=1)
 
# print() 印出資料
print(patients[['Name', 'BMI', 'BMI_Status', 'BodyFat_Pct', 'Fat_Status']])
 
# Name   BMI   BMI_Status  BodyFat_Pct Fat_Status
# Alex   26.1  ⚠️ 過重      18          ✅ 正常
# Bella  19.5  ✅ 正常範圍   32          ⚠️ 偏高
# Chris  26.0  ⚠️ 過重      26          ⚠️ 偏高
# Daisy  22.0  ✅ 正常範圍   22          ✅ 正常
  1. 步驟拆解:
  • 可以看到我們根據網路資訊的定義標準,定義了 get_bmi_category 與 get_fat_category,去計算我們 BMI 與 體脂率 。
    • Alex:BMI 是「過重」,但體脂是「正常」。
    • Bella:BMI 是「正常」,但體脂是「偏高」。
  1. 資料來源:
  • Python
  • Gemini