jho*_*jho 22 python apache-spark
我有一个包含几列的数据框.现在我想从其他2列中派生出一个新列:
from pyspark.sql import functions as F
new_df = df.withColumn("new_col", F.when(df["col-1"] > 0.0 & df["col-2"] > 0.0, 1).otherwise(0))
Run Code Online (Sandbox Code Playgroud)
有了这个,我只得到一个例外:
py4j.Py4JException: Method and([class java.lang.Double]) does not exist
Run Code Online (Sandbox Code Playgroud)
它适用于这样的一个条件:
new_df = df.withColumn("new_col", F.when(df["col-1"] > 0.0, 1).otherwise(0))
Run Code Online (Sandbox Code Playgroud)
有谁知道使用多个条件?
我正在使用Spark 1.4.
Ash*_*ynd 45
使用括号强制执行所需的运算符优先级:
F.when( (df["col-1"]>0.0) & (df["col-2"]>0.0), 1).otherwise(0)
Run Code Online (Sandbox Code Playgroud)
vj *_*san 16
当在pyspark 中时,可以使用& (for and) 和|构建多个条件 (for or),将每个表达式括在括号内很重要,这些表达式组合在一起形成条件
%pyspark
dataDF = spark.createDataFrame([(66, "a", "4"),
(67, "a", "0"),
(70, "b", "4"),
(71, "d", "4")],
("id", "code", "amt"))
dataDF.withColumn("new_column",
when((col("code") == "a") | (col("code") == "d"), "A")
.when((col("code") == "b") & (col("amt") == "4"), "B")
.otherwise("A1")).show()
Run Code Online (Sandbox Code Playgroud)
当在spark scala 中时可以与&&和||一起使用 运算符建立多个条件
//Scala
val dataDF = Seq(
(66, "a", "4"), (67, "a", "0"), (70, "b", "4"), (71, "d", "4"
)).toDF("id", "code", "amt")
dataDF.withColumn("new_column",
when(col("code") === "a" || col("code") === "d", "A")
.when(col("code") === "b" && col("amt") === "4", "B")
.otherwise("A1"))
.show()
Run Code Online (Sandbox Code Playgroud)
输出:
+---+----+---+----------+
| id|code|amt|new_column|
+---+----+---+----------+
| 66| a| 4| A|
| 67| a| 0| A|
| 70| b| 4| B|
| 71| d| 4| A|
+---+----+---+----------+
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
45094 次 |
最近记录: |