![](/img/trans.png)
[英]Sequential Dynamic filters on the same Spark Dataframe Column in Scala Spark
[英]Spark Scala: create and use column in the dataframe on the same line
当我需要数据框中的新列然后用于其他计算时,我的代码类似于:
var df: DataFrame = ...
df = df.withColumn("new_col", df.col("a") / 2)
println(df.withColumn("res", df.col("b") + df.col("new_col")).head())
如何合并成一行(并避免使用var
)?
问题是df.col()
因为我不能简单地执行以下操作,因为df
尚不存在new_col
:
df.withColumn("new_col", df.col("a"))
.withColumn("res", df.col("b") + df.col("new_col"))
.head()
我缺少一些API吗?
您可以使用$
代替df.col
来创建列; 前者将根据新数据框而不是df
推断该列:
df.withColumn("new_col", $"a")
.withColumn("res", $"b" + $"new_col")
.head()
要么:
import org.apache.spark.sql.functions.col
df.withColumn("new_col", col("a"))
.withColumn("res", col("b") + col("new_col"))
.head()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.