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: 21 additions & 7 deletions homework/m1_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,24 @@
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])
mask = arr > 25
return arr[mask]


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


def yellow_top3_stock_indices(stocks):
Expand All @@ -51,7 +57,8 @@ def yellow_top3_stock_indices(stocks):
提示:np.argsort
"""
# TODO: 你的程式碼
pass
stocks2 = np.argsort(stocks)# 這部分說的是按照庫存排序 並返回的是 index值不是排序的數值
return stocks2[::-1][:3]


def yellow_restock_cost(prices, stocks):
Expand All @@ -60,7 +67,11 @@ def yellow_restock_cost(prices, stocks):
提示:布林遮罩 + .sum()
"""
# TODO: 你的程式碼
pass
prices_mask = prices < 500
cheap_prices = prices[prices_mask]
cheap_prices_stocks = cheap_prices * 50
total_cheap_prices_stocks = cheap_prices_stocks.sum()
return total_cheap_prices_stocks


# ============================================================
Expand All @@ -77,4 +88,7 @@ def red_double11_prices(prices, stocks):
提示:np.where 可以巢狀使用
"""
# TODO: 你的程式碼
pass
prices_11 = np.where(stocks >= 100, prices * 0.7,
np.where((stocks >= 20) & (stocks <=99), prices*0.9, prices))
return prices_11

34 changes: 27 additions & 7 deletions homework/m2_pandas_cleaning.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ def green_read_csv():
提示:pd.read_csv()
"""
# TODO: 你的程式碼
pass
ras = pd.read_csv('datasets/ecommerce/orders_raw.csv')

return ras


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


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


# ============================================================
Expand All @@ -52,7 +54,9 @@ def yellow_clean_columns(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 @@ -63,7 +67,11 @@ def yellow_clean_amount(df):
提示:.str.replace() + .astype(float)
"""
# TODO: 你的程式碼
pass
new_df = df.copy()
new_df['amount'] = new_df['amount'].astype(str).str.replace('$', '', regex=False)
new_df['amount'] = new_df['amount'].astype(str).str.replace(',', '', regex=False).astype(float)

return new_df


def yellow_drop_duplicates(df):
Expand All @@ -72,7 +80,10 @@ def yellow_drop_duplicates(df):
提示:df.drop_duplicates()
"""
# TODO: 你的程式碼
pass
new_df = df.copy()
new_df = new_df.drop_duplicates()

return new_df


# ============================================================
Expand All @@ -93,4 +104,13 @@ def red_clean_orders(path):
提示:pd.to_datetime(errors='coerce')
"""
# TODO: 你的程式碼
pass
df = pd.read_csv(path)
new_df = df.copy()
new_df.columns = new_df.columns.str.strip().str.lower()
new_df['amount'] = new_df['amount'].astype(str).str.replace('$','',regex=False)
new_df['amount'] = new_df['amount'].astype(str).str.replace(',','',regex=False).astype(float)
new_df['order_date'] = pd.to_datetime(new_df['order_date'],errors='coerce')
new_df = new_df.dropna(subset= ['order_date'])
new_df = new_df.dropna(subset= ['amount'])
new_df = new_df.drop_duplicates()
return new_df
37 changes: 30 additions & 7 deletions homework/m3_pandas_advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,28 @@ def green_load_and_merge():
提示:pd.merge(how='left')
"""
# TODO: 你的程式碼
pass
orders =pd.read_csv('../datasets/ecommerce/orders_clean.csv',parse_dates=['order_date'])
customers =pd.read_csv('../datasets/ecommerce/customers.csv')
products =pd.read_csv('../datasets/ecommerce/products.csv')

full = (
orders
.merge(customers, on= 'customer_id', how= 'left')
.merge(products, on='product_id',how='left')
)
return full


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,7 +59,9 @@ def yellow_top_category(df):
提示:groupby('category')['amount'].sum()
"""
# TODO: 你的程式碼
pass
category_amount = df.groupby('category')['amount'].sum()
best_category_amount =category_amount.idxmax()
return best_category_amount


def yellow_gold_vip_stats(df):
Expand All @@ -60,7 +71,11 @@ def yellow_gold_vip_stats(df):
提示:df[df['vip_level'] == 'Gold']
"""
# TODO: 你的程式碼
pass
gold_vip = df[df['vip_level'] == 'Gold']
order_count = len(gold_vip)
total_amount = gold_vip['amount'].sum

return(order_count, total_amount)


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


# ============================================================
Expand All @@ -94,4 +110,11 @@ def red_rfm_top5(df):
提示:groupby('customer_id').agg(...)
"""
# TODO: 你的程式碼
pass
rfm = df.groupby('customer_id').agg(customer_name=('customer_name','first'),
R = ('order_date','max'),
F = ('order_id','count'),
M = ('amount','sum'))
rfm = rfm.sort_values('M',ascending=False)
rfm = rfm.reset_index()
top5 = rfm.head()
return top5
41 changes: 32 additions & 9 deletions homework/m4_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ def green_avg_by_month():
提示:df['order_date'].dt.month
"""
# TODO: 你的程式碼
pass

df = _load_data()
df['year'] = df['order_date'].dt.year
df['month']= df['order_date'].dt.month
df['weekday'] = df['order_date'].dt.day_name()
df['year_month'] = df['order_date'].dt.to_period('M')
month_avg_amount = df.groupby('month')['amount'].mean()
return month_avg_amount

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


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


# ============================================================
Expand All @@ -60,19 +68,23 @@ def yellow_monthly_revenue():
提示:set_index('order_date').resample('ME')['amount'].sum()
"""
# TODO: 你的程式碼
pass
df = _load_data()
ts = df.set_index('order_date')
month_sum_amount = ts.resample('ME')['amount'].sum()

return month_sum_amount


def yellow_rolling_avg(monthly_revenue):

"""
計算 3 個月移動平均
接收 yellow_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 @@ -81,7 +93,9 @@ def yellow_category_median(df):
提示:groupby + median + sort_values
"""
# TODO: 你的程式碼
pass
category_order_median = df.groupby('category')['amount'].median()
category_order_median = category_order_median.sort_values(ascending =False)
return category_order_median


# ============================================================
Expand All @@ -101,4 +115,13 @@ def red_monthly_report():
提示:resample + agg + pct_change
"""
# TODO: 你的程式碼
pass
df = _load_data()
ts = df.set_index('order_date')
report = ts.resample('ME').agg(
order_count=('order_id', 'count'),
revenue=('amount', 'sum'),
active_customers=('customer_id', 'nunique'),
)
report['avg_order_value'] = (report['revenue'] / report['order_count']).round(2)
report['revenue_growth'] = (report['revenue'].pct_change()*100.).round(2)
return report
Loading
Loading