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
34 changes: 27 additions & 7 deletions homework/m1_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,22 @@
def green_mean():
"""建立 [10, 20, 30, 40, 50],回傳所有元素的平均值 (float)"""
# TODO: 你的程式碼
pass
np_mean = np.array([10, 20, 30, 40, 50])
return float(np.mean(np_mean))


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


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


# ============================================================
Expand All @@ -42,7 +45,10 @@ def green_filter():
def yellow_expensive_count(prices):
"""回傳單價 > 1000 的商品數量 (int)"""
# TODO: 你的程式碼
pass
mask_expensive = prices > 1000
num_expensive = mask_expensive.sum()
return num_expensive



def yellow_top3_stock_indices(stocks):
Expand All @@ -51,7 +57,9 @@ def yellow_top3_stock_indices(stocks):
提示:np.argsort
"""
# TODO: 你的程式碼
pass
sorted_stock = np.argsort(stocks)
top3_stock = sorted_stock[-3:][::-1]
return top3_stock


def yellow_restock_cost(prices, stocks):
Expand All @@ -60,7 +68,10 @@ def yellow_restock_cost(prices, stocks):
提示:布林遮罩 + .sum()
"""
# TODO: 你的程式碼
pass
mask_cheap = prices < 500
cheap_prices = prices[mask_cheap]
total_cost = round((cheap_prices * 50).sum(), 0)
return total_cost


# ============================================================
Expand All @@ -77,4 +88,13 @@ def red_double11_prices(prices, stocks):
提示:np.where 可以巢狀使用
"""
# TODO: 你的程式碼
pass
final_price = np.where(
stocks >= 100,
prices * 0.7,
np.where(
stocks >= 20,
prices * 0.9,
prices
)
)
return final_price
50 changes: 43 additions & 7 deletions homework/m2_pandas_cleaning.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def green_read_csv():
提示:pd.read_csv()
"""
# TODO: 你的程式碼
pass
df_raw = pd.read_csv()
return df_raw


def green_shape(df):
Expand All @@ -29,7 +30,9 @@ def green_shape(df):
提示:df.shape
"""
# TODO: 你的程式碼
pass
df_shape = df.shape
return df_shape



def green_dtypes(df):
Expand All @@ -38,7 +41,8 @@ def green_dtypes(df):
提示:df.dtypes
"""
# TODO: 你的程式碼
pass
df_dtypes = df.dtypes
return df_dtypes


# ============================================================
Expand All @@ -52,7 +56,9 @@ def yellow_clean_columns(df):
提示:df.columns.str.strip().str.lower()
"""
# TODO: 你的程式碼
pass
df_clean = df.copy()
df_clean.columns = df_clean.columns.str.strip().str.lower()
return df_clean


def yellow_clean_amount(df):
Expand All @@ -63,7 +69,16 @@ def yellow_clean_amount(df):
提示:.str.replace() + .astype(float)
"""
# TODO: 你的程式碼
pass
df_clean = df.copy()
df_clean['amount'] = (
df_clean['amount']
.astype(str)
.str.replace('$', '', regex = False)
.str.replace(',', '', regex = False)
.astype(float)
)
return df_clean



def yellow_drop_duplicates(df):
Expand All @@ -72,7 +87,8 @@ def yellow_drop_duplicates(df):
提示:df.drop_duplicates()
"""
# TODO: 你的程式碼
pass
df_duplicates = df.drop_duplicates()
return df_duplicates


# ============================================================
Expand All @@ -93,4 +109,24 @@ def red_clean_orders(path):
提示:pd.to_datetime(errors='coerce')
"""
# TODO: 你的程式碼
pass
df = pd.read_csv(path)
df_before = len(df)

df_columns = df.columns.str.strip().str.lower()

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()
df_after = len(df)

print(f"清理之前{df_before},清理之後{df_after}")
print('-----------------------------')
return df
42 changes: 34 additions & 8 deletions homework/m3_pandas_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,24 @@ def green_load_and_merge():
提示:pd.merge(how='left')
"""
# TODO: 你的程式碼
pass
df = (
orders
.merge(customers, on='customer_id', how='left')
.merge(products, on='product_id', how='left')
)
return df


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


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


# ============================================================
Expand All @@ -50,8 +55,8 @@ def yellow_top_category(df):
提示:groupby('category')['amount'].sum()
"""
# TODO: 你的程式碼
pass

df_category = df.groupby('category')['amount'].sum()
return df_category.idxmax()

def yellow_gold_vip_stats(df):
"""
Expand All @@ -60,7 +65,10 @@ def yellow_gold_vip_stats(df):
提示:df[df['vip_level'] == 'Gold']
"""
# TODO: 你的程式碼
pass
gold = df[df['vip_level'] == 'Gold']
gold_count = len(gold)
gold_total = gold['amount'].sum()
return (gold_count, gold_total)


def yellow_region_avg_amount(df):
Expand All @@ -70,7 +78,13 @@ def yellow_region_avg_amount(df):
提示:groupby('region')['amount'].mean()
"""
# TODO: 你的程式碼
pass
region_mean = (
df.groupby('region')['amount']
.mean()
.round(2)
.sort_values(ascending=False)
)
return region_mean


# ============================================================
Expand All @@ -94,4 +108,16 @@ def red_rfm_top5(df):
提示:groupby('customer_id').agg(...)
"""
# TODO: 你的程式碼
pass
rfm = (
df.groupby(['customer_id', 'customer_name'])
.agg(
r = ('order_date', 'max'),
f = ('order_id', 'count'),
m = ('amount', 'sum'),
)
.reset_index()
.sort_values('m', ascending=False)
.head(5)
)

return rfm
54 changes: 47 additions & 7 deletions homework/m4_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ def green_avg_by_month():
提示:df['order_date'].dt.month
"""
# TODO: 你的程式碼
pass
avg_month = (
df.groupby(df['order_date'].dt.month)['amount']
.mean()
.round(2)
)
return avg_month


def green_top3_dates():
Expand All @@ -37,7 +42,9 @@ def green_top3_dates():
提示:value_counts().head(3)
"""
# TODO: 你的程式碼
pass
top3_dates = df['order_date'].dt.date.value_counts().head(3)
return top3_dates



def green_date_range():
Expand All @@ -46,7 +53,9 @@ def green_date_range():
格式為 pandas Timestamp
"""
# TODO: 你的程式碼
pass
earliest = df['order_date'].min()
latest = df['order_date'].max()
return (earliest, latest)


# ============================================================
Expand All @@ -60,7 +69,10 @@ def yellow_monthly_revenue():
提示:set_index('order_date').resample('ME')['amount'].sum()
"""
# TODO: 你的程式碼
pass
monthly_revenue = (
df.set_index('order_date').resample('ME')['amount'].sum()
)
return monthly_revenue


def yellow_rolling_avg(monthly_revenue):
Expand All @@ -71,7 +83,8 @@ def yellow_rolling_avg(monthly_revenue):
提示:.rolling(window=3).mean()
"""
# TODO: 你的程式碼
pass
rolling_avg = monthly_revenue.rolling(window=3).mean()
return rolling_avg


def yellow_category_median(df):
Expand All @@ -81,7 +94,13 @@ def yellow_category_median(df):
提示:groupby + median + sort_values
"""
# TODO: 你的程式碼
pass
category_median = (
df.groupby('category')['amount']
.mean()
.round(1)
.sort_values(ascending=False)
)
return category_median


# ============================================================
Expand All @@ -101,4 +120,25 @@ def red_monthly_report():
提示:resample + agg + pct_change
"""
# TODO: 你的程式碼
pass
df = _load_data()
df = df.set_index('order_date')

monthly_report = (
df.resample('ME')
.agg(
總訂單數 = ('order_id', 'count'),
總營收 = ('amount', 'sum'),
活躍客戶數 = ('customer_id', 'nunique'),
)
.sort_index()
)

monthly_report['客單價'] = (
monthly_report['總營收']/monthly_report['總訂單數']
).round(1)

monthly_report['月營收成長率'] = (
monthly_report['總營收'].pct_change() * 100
).round(2)

return monthly_report
Loading
Loading