开发者社区> 问答> 正文

Pyspark-在groupBy中分配每个组[重复]

我想在一个组中为每个组分配一个从0或1开始的唯一ID号,并使用pyspark为每个组递增1。

我之前使用pthon与python一起完成了这个命令:

df['id_num'] = (df

            .groupby('column_name')
            .grouper
            .group_info[0])

输入和所需输出的玩具示例是:

输入

object
apple
orange
pear
berry
apple
pear
berry

输出:

objectid
apple1
orange2
pear3
berry4
apple1
pear3
berry4

展开
收起
社区小助手 2018-12-19 16:35:37 4050 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    from pyspark.sql.functions import col, create_map, lit
    from itertools import chain
    values = [('apple',),('orange',),('pear',),('berry',),('apple',),('pear',),('berry',)]
    df = sqlContext.createDataFrame(values,['object'])

    Creating a column of distinct elements and converting them into dictionary with unique indexes.

    df1 = df.distinct()
    distinct_list = list(df1.select('object').toPandas()['object'])
    dict_with_index = {distinct_list[i]:i+1 for i in range(len(distinct_list))}

    Applying the mapping of dictionary.

    mapping_expr = create_map([lit(x) for x in chain(*dict_with_index.items())])
    df=df.withColumn("id", mapping_expr.getItem(col("object")))

    df.show()
    objectid
    apple2
    orange1
    pear3
    berry4
    apple2
    pear3
    berry4

    +------+---+

    2019-07-17 23:23:01
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Get rid of traditional ETL, Move to Spark! 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载