ฟังก์ชันที่กำหนดเองสำหรับสร้างกราฟ
ในแบบฝึกหัดที่แล้ว ต้องเขียนโค้ดนี้เพื่อสร้างกราฟ:
# 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()
สังเกตว่าโค้ดนี้ทำงานซ้ำในลักษณะเดิมกับทั้ง DataFrame ของ tech และ FMCG ซึ่งขัดกับหลักการเขียนโค้ดที่เรียกว่า DRY — Don't repeat yourself (อย่าเขียนโค้ดซ้ำ) โค้ดที่ซ้ำซ้อนไม่เป็นผลดี เพราะเพิ่มภาระงานและทำให้เกิดข้อผิดพลาดได้ง่ายขึ้น ในแบบฝึกหัดนี้ จะได้กำหนดฟังก์ชันของตัวเองเพื่อประมวลผลข้อมูลและสร้างกราฟ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์งบการเงินด้วย Python
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำจริง
เปลี่ยนทฤษฎีให้เป็นการลงมือทำด้วยแบบฝึกหัดเชิงโต้ตอบหนึ่งในของเรา
เริ่มแบบฝึกหัด