首页 > 解决方案 > 使用pyspark从1开始按递增顺序添加行号列

问题描述

我想创建一个名为“id”的列,其中包含要在最终生成对中使用的行号。“身份证”栏

我使用以下方式在python中完成了它。任何人都可以建议如何在pyspark中做到这一点。

con_2['id'] = range(1, 1+len(con_2))
len(con_2.customer_play_id.unique()) 

我的 Pyspark 代码如下,但它不起作用

from pyspark.sql.types import IntegerType
slen = udf(lambda s: len(s), IntegerType())
con_2 = con_2.withColumn('id', F.length(con_2.customer_play_id))

预期输出应该是(Id 是我要添加的列)df

id  col1 col2
1   X      Y
2   y1     y4
3   y2     y7
4   y3     y8

标签: pyspark

解决方案


from pyspark.sql.window import Window as W
from pyspark.sql import functions as 
con_2 =con_2.withColumn("id",row_number().over(Window.orderBy("customer_play_id")))
con_2.show()

推荐阅读