首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在pyspark dataframe中获取列的唯一值并存储为新列

如何在pyspark dataframe中获取列的唯一值并存储为新列
EN

Stack Overflow用户
提问于 2021-08-30 03:14:59
回答 1查看 84关注 0票数 0

基本上,我想知道某个客户在其他数据集中购买了多少品牌,并将其重命名为change brand,以下是我在Pandas中所做的

代码语言:javascript
复制
firstvalue=firstvalue.merge((pd.DataFrame(profile.groupby('msisdn')
                                          .handset_brand.nunique()
                                          .rename('hpbrand_change_num'))
                                          .reset_index()),how='left',on=['msisdn'])

下面是我在pyspark中所做的(没有合并)

代码语言:javascript
复制
fd_subsprofile.groupBy("msisdn")\
              .handset_brand.nunique()\
              .withColumn('hpbrand_change_num')\
              .reset_index()

错误消息

代码语言:javascript
复制
AttributeError: 'GroupedData' object has no attribute 'handset_brand'

然后,我试着

代码语言:javascript
复制
fd_subsprofile.groupBy("msisdn").select("handset_brand").count().show()

错误消息

代码语言:javascript
复制
AttributeError: 'GroupedData' object has no attribute 'select'

如何在pyspark中做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-30 04:05:08

同样的事情也可以在Pyspark中完成,如下所示-

nunique等价物- countDistinctmerge等价物- Join

代码语言:javascript
复制
import pyspark.sql.functions as F

profile_agg_sparkDF = profile.groupBy('id').agg(F.countDistinct(F.col('brand')).alias('change_brand'))

df = df.join(profile_agg_sparkDF
            ,df['id'] == profile_agg_sparkDF['id']
            ,'left'
        ).select(df['*'],profile_agg_sparkDF['change_brand'])
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68978583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档