以時間組件進行連接
你常會用日期的組件來連接其他資訊。不過在這個範例中,我們需要使用當時準備買房的人能取得的資料。這表示在分析時要使用前一年的報告資料。
本練習屬於課程
使用 PySpark 進行特徵工程
練習說明
- 使用
year()從LISTDATE萃取年份,並用withColumn()放到名為list_year的新欄位。 - 建立另一個名為
report_year的新欄位,其值為list_year減去 1。 - 建立連接條件,讓
df['CITY']對應price_df['City'],且df['report_year']對應price_df['Year']。 - 在
df與price_df之間執行 left join。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from pyspark.sql.functions import year
# Initialize dataframes
df = real_estate_df
price_df = median_prices_df
# Create year column
df = df.____(____, ____(____))
# Adjust year to match
df = df.withColumn(____, (df[____] - 1))
# Create join condition
condition = [df[____] == price_df[____], df[____] == price_df[____]]
# Join the dataframes together
df = ____.join(____, on=condition, how=____)
# Inspect that new columns are available
df[['MedianHomeValue']].show()