我是 PySpark 的新手,我发现有两种方法可以在 PySpark 中选择列,即使用“.select()”或“.withColumn()”。
据我所知,“.withColumn()”的性能较差,但除此之外,我很困惑为什么有两种方法可以做同样的事情。
那么我什么时候应该使用“.select()”而不是“.withColumn()”?
我用谷歌搜索过这个问题,但没有找到明确的解释。
使用:
df.withColumn('new', func('old'))
Run Code Online (Sandbox Code Playgroud)
你的 Spark 处理代码在哪里func,相当于:
df.select('*', func('old').alias('new')) # '*' selects all existing columns
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,withColumn()使用起来非常方便(可能是它可用的原因),但是正如您所指出的,存在性能影响。有关详细信息,请参阅此文章:Spark DAG diffs with 'withColumn' vs 'select'