本文向您展示如何使用Apache Spark函数在列中生成唯一的递增数值。
我们回顾三种不同的使用方法。您应该选择最适合您的用例的方法。
使用zipWithIndex ()在弹性分布式数据集中(RDD)
的zipWithIndex ()函数仅在rdd内可用。你不能直接在数据帧上使用它。
将您的DataFrame转换为RDD,应用zipWithIndex ()然后将RDD转换回DataFrame。
我们将使用下面的示例代码向一个有两个条目的基本表添加唯一id号。
%python df = spark。createDataFrame([(“爱丽丝”,“10”)(“苏珊”,“12”)],[“名称”,“年龄”])df1 = df.rdd.zipWithIndex () .toDF () df2 = df1.select(坳(“_1。*”)(“_2”).alias上校(increasing_id)) df2.show ()
运行示例代码,我们得到以下结果:
+-----+---+-------------+ | 姓名|年龄| increasing_id | +-----+---+-------------+ | 苏珊爱丽丝| 10 | 0 | | | 12 | 1 | +-----+---+-------------+
使用monotonically_increasing_id ()用于唯一的,但不是连续的数字
的monotonically_increasing_id ()函数生成单调递增的64位整数。
生成的id号保证是递增的且唯一的,但不保证是连续的。
我们将使用下面的示例代码向一个有两个条目的基本表单调递增添加id号。
%python from pyspark.sql.functions导入* df_with_increing_id = df。与Column("monotonically_increasing_id", monotonically_increasing_id()) df_with_increasing_id.show()
运行示例代码,我们得到以下结果:
+-----+---+---------------------------+ | 姓名|年龄| monotonically_increasing_id | +-----+---+---------------------------+ | 苏珊爱丽丝10 | | 8589934592 | | | | 12 25769803776 | +-----+---+---------------------------+
结合monotonically_increasing_id ()与row_number ()对于两列
的row_number ()函数生成连续的数。
将此与monotonically_increasing_id ()生成两列可用于识别数据条目的数字。
我们将使用下面的示例代码将id号和行号单调递增地添加到一个有两个条目的基本表中。
%python from pyspark.sql.functions import * from pyspark.sql.window import * window = window . orderby (col('单调ally_increing_id ')) df_with_consecutive_increing_id = df_with_increing_id。withColumn(' increing_id ', row_number().over(window))
运行示例代码,我们得到以下结果:
+-----+---+---------------------------+-------------+ | 姓名|年龄| monotonically_increasing_id | increasing_id | +-----+---+---------------------------+-------------+ | 苏珊爱丽丝| 10 | 8589934592 | 1 | | | 25769803776 | | 12 2 | +-----+---+---------------------------+-------------+
如果需要根据最近更新的最大值进行递增,则可以定义之前的最大值,然后从那里开始计数。
我们将在刚才运行的示例代码上进行构建。
首先,我们需要定义值previous_max_value.通常通过从现有的输出表中获取值来实现这一点。在本例中,我们将其定义为1000。
df_with_consecutive_increing_id . %python previous_max_value = 1000与Column("cnsecutiv_increase", col("increasing_id") + lit(previous_max_value)).show()
当这与前面的示例代码结合并运行时,我们得到以下结果:
+-----+---+---------------------------+-------------+------------------+ | 姓名|年龄| monotonically_increasing_id | increasing_id | cnsecutiv_increase | +-----+---+---------------------------+-------------+------------------+ | 爱丽丝| 1001 | 8589934592 | 1 | | |苏珊| 1002 | 25769803776 | 2 | | +-----+---+---------------------------+-------------+------------------+