開始使用免費開始

自訂函式來繪圖

在上一個練習中,你必須撰寫以下程式碼來產生圖表:

# Subset tech and fmcg companies
subset_dat = dataset.loc[dataset["comp_type"].isin(["tech", "fmcg"])]

# Compute yearly average gross margin ratio of tech and fmcg companies
subset_dat_avg = subset_dat.pivot_table(index=["Year", "comp_type"], values = "gross_margin").reset_index()

# Add column company
subset_dat_avg["company"] = np.where(subset_dat_avg["comp_type"]=="tech", "Avg tech", "Avg fmcg")

# Concat the DataFrames
plot_df = pd.concat([subset_dat, subset_dat_avg], axis=0)

# Make the plot
sns.relplot(data=plot_df.reset_index(drop=True), x="Year", y="gross_margin", hue="company", col="comp_type", kind="line")
plt.show()
plt.close()

請注意,在這個練習中我們對 tech 與 FMCG 的 DataFrame 做了相同的處理。這很重複,違反了稱為 DRY(Don't repeat yourself,不要重複自己)的程式設計原則。重複的程式碼會增加你的工作量,也更容易出錯。在本練習中,你將自訂一個函式來處理資料並繪製圖形。

本練習屬於課程

使用 Python 分析財務報表

檢視課程

動手互動練習

將理論付諸實踐,立即體驗我們的互動練習

開始練習