危險的連接
在這個練習中,我們要用緯度(Latitude)與經度(Longitude)來連接另一個資料集,該資料集衡量社區對步行的友善程度。你需要特別留意連接欄位的資料型別必須一致,且小數精度(小數點後的位數)要相同,否則連接不會成功!
下面你會看到 df['latitude'] 與 df['longitude'] 的精度高於 walk_df['longitude'] 與 walk_df['latitude']。我們需要把它們四捨五入到相同的精度,連接才會正確運作。
本練習屬於課程
使用 PySpark 進行特徵工程
練習說明
- 透過在欄位上使用
cast('double')並用withColumn()就地取代欄位,把walk_df['latitude']和walk_df['longitude']轉成 double 型別。 - 使用
withColumn(),搭配round('latitude', 5)與round('longitude', 5)就地四捨五入這兩個欄位。 - 建立連接條件:
walk_df['latitude']要對上df['latitude'],而walk_df['longitude']要對上df['longitude']。 - 使用
join()依照上述條件,並指定left連接型態,將df與walk_df連接。把結果資料框存成join_df。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Cast data types
walk_df = ____.withColumn('longitude', ____.cast('double'))
walk_df = ____.withColumn(____, ____.cast('double'))
# Round precision
df = df.withColumn('longitude', round(____, 5))
df = df.withColumn(____, round(____, 5))
# Create join condition
condition = [____ == ____, ____ == ____]
# Join the dataframes together
join_df = ____.join(____, on=____, how=____)
# Count non-null records from new field
print(join_df.where(~join_df['walkscore'].isNull()).count())