我有一个dataframe值,如
-------------
| col1 | col2 |
-------------
| a | 2 |
| b | 3 |
| c | 4 |
| d | 5 |
-------------我希望创建第三列,该列具有从指定数字开始的自动递增值。
假设我希望数字从5开始,那么预期的输出应该是
--------------------
| col1 | col2 | col3 |
|--------------------|
| a | 2 | 5 |
| b | 3 | 6 |
| c | 4 | 7 |
| d | 5 | 8 |
--------------------我尝试过monotonically_increasing_id(),但由于分区而没有给出序列号,而且它也没有从指定的编号开始的特性。
我正在使用Spark2.4.5和Pyspark (python)。
发布于 2020-03-04 02:41:43
我们可以使用窗口函数row_number和orderby()(用于全局排序)子句,并添加4从5开始序列
火花放电中的
:
Using row_number():
from pyspark.sql.window import Window
from pyspark.sql.functions import *
df=spark.createDataFrame([('a',2),('b',3),('c',4),('d',5)],['col1','col2']).repartition(4)
w=Window.orderBy('col2')
df.withColumn("col3",row_number().over(w) + 4).show()
#+----+----+----+
#|col1|col2|col3|
#+----+----+----+
#| a| 2| 5|
#| b| 3| 6|
#| c| 4| 7|
#| d| 5| 8|
#+----+----+----+In Scala:
val w = Window.orderBy("col2")
df.withColumn("col3", row_number().over(w) + 4).show()
//+----+----+----+
//|col1|col2|col3|
//+----+----+----+
//| a| 2| 5|
//| b| 3| 6|
//| c| 4| 7|
//| d| 5| 8|
//+----+----+----+https://stackoverflow.com/questions/60518253
复制相似问题