pyspark中的withclomn错误:TypeError:“列”对象不可调用

时间:2018-12-14 22:24:39

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

我正在使用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

可以帮助解决这个错误。

2 个答案:

答案 0 :(得分:1)

这是因为您试图将功能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"))

答案 1 :(得分:0)

您应该使用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|
+--------+------+---+-----+-----+----+--------+