【问题标题】:contains pyspark SQL: TypeError: 'Column' object is not callable包含 pyspark SQL: TypeError: 'Column' object is not callable
【发布时间】:2018-12-14 22:24:39
【问题描述】:

我使用的是 spark 2.0.1,

 df.show()
+--------+------+---+-----+-----+----+
|Survived|Pclass|Sex|SibSp|Parch|Fare|
+--------+------+---+-----+-----+----+
|     0.0|   3.0|1.0|  1.0|  0.0| 7.3|
|     1.0|   1.0|0.0|  1.0|  0.0|71.3|
|     1.0|   3.0|0.0|  0.0|  0.0| 7.9|
|     1.0|   1.0|0.0|  1.0|  0.0|53.1|
|     0.0|   3.0|1.0|  0.0|  0.0| 8.1|
|     0.0|   3.0|1.0|  0.0|  0.0| 8.5|
|     0.0|   1.0|1.0|  0.0|  0.0|51.9|

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

>>> dfnew = df.withColumn('AddCol' , when(df.Pclass.contains('3.0'),'three').otherwise('notthree'))

报错

TypeError: 'Column' object is not callable

可以帮助解决这个错误。

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql


    【解决方案1】:

    这是因为您试图将函数 contains 应用于列。 pyspark 中不存在函数contains。你应该试试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"))
    

    【讨论】:

    • 函数contains在文档中描述,没有任何X.X版本中的新功能警告as seen here。知道为什么不可用吗?
    • 在这种情况下,用户使用的是 pyspark 2.0.1,其中包含不可用。检查您的 pyspark 版本,因为 contains 仅适用于 2.2 及更高版本。干杯。
    【解决方案2】:

    你应该使用 df.col(colName) 而不是 df.colName

    使用 java 8 和 spark 2.1 的示例:

    df.show();
    
    +--------+------+---+-----+-----+----+
    |Survived|Pclass|Sex|SibSp|Parch|Fare|
    +--------+------+---+-----+-----+----+
    |       0|     3|  1|    1|    0|   3|
    |       1|     1|  0|    1|    0|   2|
    +--------+------+---+-----+-----+----+
    
    df = df.withColumn("AddCol", when(df.col("Pclass").contains("3"),"three").otherwise("notthree"));
    
    df.show();
    
    +--------+------+---+-----+-----+----+--------+
    |Survived|Pclass|Sex|SibSp|Parch|Fare|  AddCol|
    +--------+------+---+-----+-----+----+--------+
    |       0|     3|  1|    1|    0|   3|   three|
    |       1|     1|  0|    1|    0|   2|notthree|
    +--------+------+---+-----+-----+----+--------+
    

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2018-03-31
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 2022-08-23
      • 2022-12-26
      相关资源
      最近更新 更多