[monotonically_increasing_id大于数据框中的总记录数

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

我下面有pyspark代码。我正在尝试创建一个不断增加的新match_id。旧的match_id是随机的唯一值。 match_id表示数据中匹配的产品对。因此,我将按ID对原始数据进行排序。可以有多个ID对应一个match_id。我为每个match_id取第一个ID。然后按ID对第一个ID和match_id的较小数据框进行排序。然后,我要创建一个新的单调递增的id。然后,我重新加入到match_id上的原始数据帧,因此可以使原始数据帧具有新的单调增加的match_id。我遇到的问题是,新的match_id的值大于任一数据帧中的记录数。那怎么可能呢? new_match_id不应该等于id_to_match_id加1的行号吗?那么最大的new_match_id应该是377729?有人可以解释造成这些新的new_match_id的原因并建议我如何正确创建new_match_id吗?

代码:

# partition by match_id and get first id


w2 = Window().partitionBy("match_id").orderBy(new_matched_df.id.asc())

id_to_match_id=new_matched_df\
.select(col("match_id"), first("id",True).over(w2).alias('id')).distinct()

# creating new match_id

from pyspark.sql.functions import monotonically_increasing_id

id_to_match_id=id_to_match_id.sort('id',ascending=True).withColumn('new_match_id',(monotonically_increasing_id()+1))


new_matched_df2=new_matched_df

# replacing old match_id with new match_id
new_matched_df2=new_matched_df2.alias('a')\
.join(id_to_match_id.alias('b'),
     (col('a.match_id')==col('b.match_id')),
      how='inner'
     )\
.select(col('a.storeid'),
        col('a.product_id'),
        col('a.productname'),
        col('a.productbrand'),
        col('a.producttype'),
        col('a.productsubtype'),
        col('a.classification'),
        col('a.weight'),
        col('a.unitofmeasure'),
        col('a.id'),
        col('b.new_match_id').alias('match_id'))


id_to_match_id.sort('new_match_id',ascending=False).show()


print(new_matched_df2.count())

print(id_to_match_id.count())

输出:

+------------+------+-------------+
|    match_id|    id| new_match_id|
+------------+------+-------------+
|412316878198|864316|1709396985719|
|412316878188|864306|1709396985718|
|412316878183|864301|1709396985717|
|412316878182|864300|1709396985716|
|412316878181|864299|1709396985715|
|412316878178|864296|1709396985714|
|412316878177|864295|1709396985713|
|412316878175|864293|1709396985712|
|412316878174|864292|1709396985711|
|412316878169|864287|1709396985710|
|412316878160|864278|1709396985709|
|412316878156|864274|1709396985708|
|412316878154|864272|1709396985707|
|412316878149|864267|1709396985706|
|412316878148|864266|1709396985705|
|412316878146|864264|1709396985704|
|412316878145|864263|1709396985703|
|412316878143|864261|1709396985702|
|412316878136|864254|1709396985701|
|412316878135|864253|1709396985700|
+------------+------+-------------+


864302
377728
apache-spark pyspark pyspark-sql
1个回答
0
投票

您好,请检查this

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