我正在使用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
这是因为您正在尝试将该函数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
df = df.withColumn("AddCol",F.when(F.col("Pclass") == F.lit(3),"three").otherwise("notthree"))
df = df.withColumn("AddCol",F.when(F.col("Pclass") == F.lit("3"),"three").otherwise("notthree"))