在 Pyspark 数据框中批量添加唯一 id 到行

问题描述 投票:0回答:1

我有一个 PySpark 数据框,我需要在行批次中添加具有唯一 id 的新列。 例如。我需要生成唯一的 id 并将其分配给第一组 100 行,然后为每批 100 行依此类推。

我怎样才能有效地完成这件事?

python apache-spark pyspark
1个回答
0
投票

我希望我能很好地理解你的问题。

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。

© www.soinside.com 2019 - 2024. All rights reserved.