开发者社区> 问答> 正文

withclomn in pyspark错误:TypeError:'Column'对象不可调用

我正在使用spark 2.0.1,

df.show()
SurvivedPclassSexSibSpParchFare
0.03.01.01.00.07.3
1.01.00.01.00.071.3
1.03.00.00.00.07.9
1.01.00.01.00.053.1
0.03.01.00.00.08.1
0.03.01.00.00.08.5
0.01.01.00.00.051.9

我有一个数据框,我想使用withColumn向df添加一个新列,新列的值基于其他列值。我用过这样的东西:

dfnew = df.withColumn('AddCol' , when(df.Pclass.contains('3.0'),'three').otherwise('notthree'))
这是一个错误

TypeError: 'Column' object is not callable

展开
收起
社区小助手 2018-12-21 11:10:30 9089 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    这是因为您正在尝试将该函数contains应用于该列。该功能contains在pyspark中不存在。你应该试试like。试试这个:

    import pyspark.sql.functions as F

    df = df.withColumn("AddCol",F.when(F.col("Pclass").like("3"),"three").otherwise("notthree"))
    或者,如果您只是想让它成为数字3,应该做:

    import pyspark.sql.functions as F

    If the column Pclass is numeric

    df = df.withColumn("AddCol",F.when(F.col("Pclass") == F.lit(3),"three").otherwise("notthree"))

    If the column Pclass is string

    df = df.withColumn("AddCol",F.when(F.col("Pclass") == F.lit("3"),"three").otherwise("notthree"))

    2019-07-17 23:23:18
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spark SQL: Past, Present and Future 立即下载
Spark SQL:Past Present &Future 立即下载
Speeding up Spark with Data Co 立即下载