การเพิ่ม custom expression
ทีมของคุณมักคำนวณ metric ต่อผู้ฟังในรายงานต่าง ๆ อยู่เสมอ เพื่อให้รูปแบบนี้นำกลับมาใช้ใหม่ได้สะดวกยิ่งขึ้น ให้สร้าง custom expression ที่สามารถเชื่อมต่อแบบ method chaining ได้เหมือนกับ method ในตัวของ Polars
โหลด polars เป็น pl แล้ว และมี DataFrame ชื่อ spotify ที่มีข้อมูล streaming ของอัลบั้มพร้อมใช้งาน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การแปลงข้อมูลด้วย Polars
คำแนะนำการฝึกหัด
- กำหนด
per_listener()ให้หาร input ด้วยคอลัมน์monthly_listeners - เชื่อม function เข้ากับ
pl.Exprเพื่อให้ใช้ method chaining ได้ - นำ custom method ไปใช้กับคอลัมน์
streams
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define the per_listener function
def per_listener(input):
return ____ / pl.col("____")
# Attach the function to pl.Expr
pl.Expr.____ = ____
# Use the custom method on the streams column
result = spotify.with_columns(
pl.col("____").____().alias("streams_per_listener")
)
print(result.head())