我有一个 PySpark 数据框,我需要在行批次中添加具有唯一 id 的新列。 例如。我需要生成唯一的 id 并将其分配给第一组 100 行,然后为每批 100 行依此类推。
我怎样才能有效地完成这件事?
我希望我能很好地理解你的问题。
from pyspark.sql.functions import monotonically_increasing_id
df = df.withColumn("id", monotonically_increasing_id())
# This creates a new column 'batch_id' which assigns the same id for each batch of 100 rows
df = df.withColumn("batch_id", (df["id"] / 100).cast("integer"))
monotonically_increasing_id() 将为每一行创建一个唯一的 id。