PySpark:在某些情况下,为什么我不能将列称为属性? [英] PySpark: In certain situations, why am I not able to refer to columns as attributes?

查看:31
本文介绍了PySpark:在某些情况下,为什么我不能将列称为属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

df = df \
    .withColumn('this_month_sales', df.units * df.rate) \
    .withColumn('this_year_sales_v1', df.this_month_sales + df.sales_till_last_month) \
    .withColumn('this_year_sales_v2', F.col('this_month_sales') + df.sales_till_last_month)

在这段代码中,

  • this_year_sales_v1 的公式将导致失败,指出 this_month_sales 列不存在或不是属性或类似的东西.
  • this_year_sales_v2 的公式有效
  • formula for this_year_sales_v1 will cause a failure saying this_month_sales column doesn't exist or is not an attribute or something similar.
  • formula for this_year_sales_v2 will work

为什么?他们本质上不是在做同样的事情吗?

Why though? Aren't they doing the same thing essentially?

推荐答案

那是因为在第三行中,this_month_sales 列在原始 df 中不存在.只在第二行创建,但是df变量的属性还没有更新.

That's because in the third line, the this_month_sales column does not exist in the original df. It was only created in the second line, but the attributes of the df variable has not been updated yet.

如果你做类似的事情

df = df \
    .withColumn('this_month_sales', df.units * df.rate)

df = df \
    .withColumn('this_year_sales_v1', df.this_month_sales + df.sales_till_last_month)

那么它应该可以工作,因为当第二行运行时,this_month_sales 列现在是 df 的一个属性.

Then it should work because the this_month_sales column is now an attribute of df when the second line is run.

总的来说,我更喜欢使用 F.col 来防止此类问题.

In general, I prefer using F.col to prevent this kind of problems.

这篇关于PySpark:在某些情况下,为什么我不能将列称为属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆