我有一个像这样的数据集:
a = sc.parallelize([[1,2,3],[0,2,1],[9,8,7]]).toDF(["one", "two", "three"])
我想要一个包含新列的数据集,该列的值等于其他三列中最大的值。 输出应如下所示:
+----+----+-----+-------+
|one |two |three|max_col|
+----+----+-----+-------+
| 1| 2| 3| 3|
| 0| 2| 1| 2|
| 9| 8| 7| 9|
+----+----+-----+-------+
我想使用withColumn
,代码如下:
b = a.withColumn("max_col", max(a["one"], a["two"], a["three"]))
但是这会产生错误。
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.
奇怪。 max
返回一个 bool
吗?根据 max
的文档,显然不是这样。好吧,很奇怪。
我觉得这很奇怪:
b = a.withColumn("max_col", a["one"] + a["two"] + a["three"]))
它能够工作的事实让我更加坚信 max
的行为某种程度上是我不理解的。
我还尝试了 b = a.withColumn("max_col", max([a["one"], a["two"], a["three"]]))
,它将三个列作为列表传递而不是三个单独的元素。这与上面的错误相同。