withColumn不允许我使用max()函数生成新列

Kat*_*ler 4 python apache-spark apache-spark-sql pyspark

我有这样的数据集:

a = sc.parallelize([[1,2,3],[0,2,1],[9,8,7]]).toDF(["one", "two", "three"])
Run Code Online (Sandbox Code Playgroud)

我想要一个数据集添加一个新列,该列等于其他三列中的最大值.输出看起来像这样:

+----+----+-----+-------+
|one |two |three|max_col|
+----+----+-----+-------+
|   1|   2|    3|      3|
|   0|   2|    1|      2|
|   9|   8|    7|      9|
+----+----+-----+-------+
Run Code Online (Sandbox Code Playgroud)

我以为我会用withColumn,就像这样:

b = a.withColumn("max_col", max(a["one"], a["two"], a["three"]))
Run Code Online (Sandbox Code Playgroud)

但这会产生错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/spark152/python/pyspark/sql/column.py", line 418, in __nonzero__
    raise ValueError("Cannot convert column into bool: please use '&' for 'and', '|' for 'or', "
ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.
Run Code Online (Sandbox Code Playgroud)

奇.是否max返回bool?不是根据文件max.好的.奇怪的.

我觉得这很奇怪:

b = a.withColumn("max_col", a["one"] + a["two"] + a["three"]))
Run Code Online (Sandbox Code Playgroud)

而且它的工作原理让我更加强烈地思考,这max是我不理解的某种方式.

我也试过b = a.withColumn("max_col", max([a["one"], a["two"], a["three"]])),它将三列作为列表而不是3个separte元素传递.这产生与上面相同的错误.

zer*_*323 7

其实你在这里需要的greatest不是max:

from pyspark.sql.functions import greatest

a.withColumn("max_col", greatest(a["one"], a["two"], a["three"]))
Run Code Online (Sandbox Code Playgroud)

只是为了完整性,您可以使用least以找到最小值:

from pyspark.sql.functions import least

a.withColumn("min_col", least(a["one"], a["two"], a["three"]))
Run Code Online (Sandbox Code Playgroud)

关于错误,你会发现它非常简单.max取决于丰富的比较.当您比较两列时,您会得到Column:

type(col("a") < col("b")
## pyspark.sql.column.Column
Run Code Online (Sandbox Code Playgroud)

PySpark明确禁止将列转换为布尔值(您可以检查Column.__nonzero__源),因为它毫无意义.它只是一个逻辑表达式,无法在驱动程序上下文中进行评估.