输入DF
col1 col2 ..... coln
1 1
1 2
1 . 3
2 . 1
2 . 2
我正在尝试添加一个新列,应该是
1. "max" for all the rows of the combination (col1 , max(col2),...coln)
2. "not_max" otherwise
输出DF:
col1 . col2 . new_col ..... coln
1 1 not_max
1 . 2 . not_max
1 3 . max
2 . 1 . not_max
2 . 2 . max
我可以通过使用 groupBy 和这个新列创建一个新的 DF 并连接回原始 DF 来组合它来做到这一点。关于如何直接实施的任何建议。谢谢。
您可以使用max
sql 窗口函数一次性完成此操作,并将计算结果max
与col2
:
df.selectExpr("*",
"case when col2 = max(col2) over (partition by col1)" +
"then 'max' else 'not max' end as new_col"
).show
+----+----+----+-------+
|col1|col2|col3|new_col|
+----+----+----+-------+
| 1| 1| 1|not max|
| 1| 2| 2|not max|
| 1| 3| 1| max|
| 2| 1| 1|not max|
| 2| 2| 3| max|
+----+----+----+-------+
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句