为什么我使用 df.select(dayofyear(df['Date']))['dayofyear(Date)'] 而不是 withColumn('Days', dayofyear(df['Date']))?

Why I get an exception with df.select(dayofyear(df['Date']))['dayofyear(Date)'] but not with withColumn('Days', dayofyear(df['Date']))?

很抱歉标题太长了,但正如网站所建议的那样,这是我的问题。在处理 PySpark DataFrame 时,我想从 dfDate column 中提取日期DataFrame 并将其添加到名为 new_df 的新 DataFrame 中。所以我写道:

new_df = new_df.withColumn('Days', df.select(dayofyear(df['Date']))['dayofyear(Date)'])

但我收到一个异常消息“已解决的属性(s)dayofyear(Date)#5502 missing from ...”(消息太长)。但是当我使用 :

new_df = new_df.withColumn('Days', dayofyear(df['Date']))

完美运行。

我希望你能帮助我理解为什么这两种语法的工作方式不同。

提前致谢。

为什么要让事情变得复杂 - 首先根据需要转换日期列,然后 return 新数据帧中的结果数据帧列

df = df.withColumn("day_of_year", F.dayofyear("Date"))
df_new = df.select("day_of_year")