按时间组件进行连接
在很多情况下,您会用日期的组成部分来连接其他信息集。不过在这个示例中,我们需要使用当时打算买房的人可以获得的数据。也就是说,分析时要使用上一年度的报告数据。
本练习是课程的一部分
使用 PySpark 进行特征工程
练习说明
- 使用
year()从LISTDATE中提取年份,并通过withColumn()放入名为list_year的新列中。 - 通过在
list_year的基础上减去 1,创建名为report_year的另一列。 - 创建连接条件,使
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()