Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions homework/m1_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,20 @@

def green_mean():
"""建立 [10, 20, 30, 40, 50],回傳所有元素的平均值 (float)"""
# TODO: 你的程式碼
pass
arr = np.array([10, 20, 30, 40, 50])
return arr.mean()


def green_double():
"""建立 [10, 20, 30, 40, 50],回傳所有元素乘以 2 的 ndarray"""
# TODO: 你的程式碼
pass
arr = np.array([10, 20, 30, 40, 50])
return arr * 2


def green_filter():
"""建立 [10, 20, 30, 40, 50],回傳大於 25 的元素 (ndarray)"""
# TODO: 你的程式碼
pass
arr = np.array([10, 20, 30, 40, 50])
return arr[arr > 25]


# ============================================================
Expand All @@ -41,26 +41,23 @@ def green_filter():

def yellow_expensive_count(prices):
"""回傳單價 > 1000 的商品數量 (int)"""
# TODO: 你的程式碼
pass
return int((prices > 1000).sum())


def yellow_top3_stock_indices(stocks):
"""
回傳庫存最多的前 3 個商品的索引位置 (ndarray, 由大到小排)
提示:np.argsort
"""
# TODO: 你的程式碼
pass
return np.argsort(stocks)[-3:][::-1]


def yellow_restock_cost(prices, stocks):
"""
單價 < 500 的商品,每種各進貨 50 個,回傳總花費 (float/int)
提示:布林遮罩 + .sum()
"""
# TODO: 你的程式碼
pass
return (prices[prices < 500] * 50).sum()


# ============================================================
Expand All @@ -76,5 +73,8 @@ def red_double11_prices(prices, stocks):
回傳每個商品的雙 11 售價 (ndarray)
提示:np.where 可以巢狀使用
"""
# TODO: 你的程式碼
pass
return np.where(
stocks >= 100,
prices * 0.7,
np.where(stocks >= 20, prices * 0.9, prices)
)
54 changes: 40 additions & 14 deletions homework/m2_pandas_cleaning.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,23 @@ def green_read_csv():
讀取 orders_raw.csv,回傳原始 DataFrame(不做任何清理)
提示:pd.read_csv()
"""
# TODO: 你的程式碼
pass
return pd.read_csv("datasets/ecommerce/orders_raw.csv")


def green_shape(df):
"""
回傳 DataFrame 的 (列數, 欄數) tuple
提示:df.shape
"""
# TODO: 你的程式碼
pass
return df.shape


def green_dtypes(df):
"""
回傳 DataFrame 的欄位型別 (Series)
提示:df.dtypes
"""
# TODO: 你的程式碼
pass
return df.dtypes


# ============================================================
Expand All @@ -51,8 +48,9 @@ def yellow_clean_columns(df):
回傳清理後的 DataFrame(不要修改原始 df)
提示:df.columns.str.strip().str.lower()
"""
# TODO: 你的程式碼
pass
new_df = df.copy()
new_df.columns = new_df.columns.str.strip().str.lower()
return new_df


def yellow_clean_amount(df):
Expand All @@ -62,17 +60,23 @@ def yellow_clean_amount(df):
回傳清理後的 DataFrame(不要修改原始 df)
提示:.str.replace() + .astype(float)
"""
# TODO: 你的程式碼
pass
new_df = df.copy()
new_df["amount"] = (
new_df["amount"]
.astype(str)
.str.replace("$", "", regex=False)
.str.replace(",", "", regex=False)
.astype(float)
)
return new_df


def yellow_drop_duplicates(df):
"""
移除完全重複的列,回傳去重後的 DataFrame
提示:df.drop_duplicates()
"""
# TODO: 你的程式碼
pass
return df.drop_duplicates().copy()


# ============================================================
Expand All @@ -92,5 +96,27 @@ def red_clean_orders(path):
回傳:清理後的 DataFrame
提示:pd.to_datetime(errors='coerce')
"""
# TODO: 你的程式碼
pass
df = pd.read_csv(path)

# 欄位名稱清理
df.columns = df.columns.str.strip().str.lower()

# amount 清理
df["amount"] = (
df["amount"]
.astype(str)
.str.replace("$", "", regex=False)
.str.replace(",", "", regex=False)
.astype(float)
)

# 日期轉換
df["order_date"] = pd.to_datetime(df["order_date"], errors="coerce")

# 刪除關鍵欄位缺值
df = df.dropna(subset=["amount", "order_date"])

# 去重
df = df.drop_duplicates()

return df.copy()
57 changes: 43 additions & 14 deletions homework/m3_pandas_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,23 @@ def green_load_and_merge():
- 再 LEFT JOIN products.csv ON product_id
提示:pd.merge(how='left')
"""
# TODO: 你的程式碼
pass
orders = pd.read_csv("datasets/ecommerce/orders_clean.csv")
customers = pd.read_csv("datasets/ecommerce/customers.csv")
products = pd.read_csv("datasets/ecommerce/products.csv")

df = pd.merge(orders, customers, on="customer_id", how="left")
df = pd.merge(df, products, on="product_id", how="left")
return df


def green_row_count(df):
"""回傳 DataFrame 的列數 (int)"""
# TODO: 你的程式碼
pass
return int(len(df))


def green_column_list(df):
"""回傳 DataFrame 的所有欄位名稱 (list)"""
# TODO: 你的程式碼
pass
return list(df.columns)


# ============================================================
Expand All @@ -49,8 +52,8 @@ def yellow_top_category(df):
回傳該類別名稱 (str)
提示:groupby('category')['amount'].sum()
"""
# TODO: 你的程式碼
pass
revenue_by_cat = df.groupby("category")["amount"].sum()
return revenue_by_cat.idxmax()


def yellow_gold_vip_stats(df):
Expand All @@ -59,8 +62,10 @@ def yellow_gold_vip_stats(df):
回傳 tuple: (訂單數 int, 總金額 float)
提示:df[df['vip_level'] == 'Gold']
"""
# TODO: 你的程式碼
pass
sub = df[df["vip_level"] == "Gold"]
order_count = int(len(sub))
total_amount = float(sub["amount"].sum())
return order_count, total_amount


def yellow_region_avg_amount(df):
Expand All @@ -69,8 +74,7 @@ def yellow_region_avg_amount(df):
回傳 Series(index=region, values=平均金額)
提示:groupby('region')['amount'].mean()
"""
# TODO: 你的程式碼
pass
return df.groupby("region")["amount"].mean()


# ============================================================
Expand All @@ -93,5 +97,30 @@ def red_rfm_top5(df):

提示:groupby('customer_id').agg(...)
"""
# TODO: 你的程式碼
pass
data = df.copy()

# 確保日期型別可比較
data["order_date"] = pd.to_datetime(data["order_date"], errors="coerce")

agg = (
data.groupby("customer_id")
.agg(
R=("order_date", "max"),
F=("order_date", "count"),
M=("amount", "sum"),
)
.reset_index()
)

# 取每位客戶的名稱(假設同一 customer_id 對應唯一名稱)
names = (
data[["customer_id", "customer_name"]]
.drop_duplicates(subset=["customer_id"])
)

result = pd.merge(agg, names, on="customer_id", how="left")

result = result[["customer_id", "customer_name", "R", "F", "M"]]
result = result.sort_values("M", ascending=False).head(5)

return result.reset_index(drop=True)
40 changes: 26 additions & 14 deletions homework/m4_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def green_avg_by_month():
回傳 Series(index=月份 1~12, values=平均金額)
提示:df['order_date'].dt.month
"""
# TODO: 你的程式碼
pass
df = _load_data()
return df.groupby(df["order_date"].dt.month)["amount"].mean()


def green_top3_dates():
Expand All @@ -36,17 +36,17 @@ def green_top3_dates():
回傳 Series(index=日期, values=訂單數, 由多到少排序)
提示:value_counts().head(3)
"""
# TODO: 你的程式碼
pass
df = _load_data()
return df["order_date"].dt.date.value_counts().head(3)


def green_date_range():
"""
回傳資料的日期範圍 tuple: (最早日期, 最晚日期)
格式為 pandas Timestamp
"""
# TODO: 你的程式碼
pass
df = _load_data()
return df["order_date"].min(), df["order_date"].max()


# ============================================================
Expand All @@ -59,8 +59,8 @@ def yellow_monthly_revenue():
回傳 Series(index=月底日期 period, values=總營收)
提示:set_index('order_date').resample('ME')['amount'].sum()
"""
# TODO: 你的程式碼
pass
df = _load_data()
return df.set_index("order_date").resample("ME")["amount"].sum()


def yellow_rolling_avg(monthly_revenue):
Expand All @@ -70,8 +70,7 @@ def yellow_rolling_avg(monthly_revenue):
回傳 Series(同樣 index,values=移動平均,前 2 筆可為 NaN)
提示:.rolling(window=3).mean()
"""
# TODO: 你的程式碼
pass
return monthly_revenue.rolling(window=3).mean()


def yellow_category_median(df):
Expand All @@ -80,8 +79,7 @@ def yellow_category_median(df):
回傳 Series(index=category, values=中位數)
提示:groupby + median + sort_values
"""
# TODO: 你的程式碼
pass
return df.groupby("category")["amount"].median().sort_values(ascending=False)


# ============================================================
Expand All @@ -100,5 +98,19 @@ def red_monthly_report():
index 為月份 (period 或 datetime)
提示:resample + agg + pct_change
"""
# TODO: 你的程式碼
pass
df = _load_data()

monthly = (
df.set_index("order_date")
.resample("ME")
.agg(
order_count=("amount", "count"),
revenue=("amount", "sum"),
active_customers=("customer_id", "nunique"),
)
)

monthly["avg_order_value"] = monthly["revenue"] / monthly["order_count"]
monthly["revenue_growth"] = monthly["revenue"].pct_change()

return monthly
Loading
Loading