【问题标题】:GroupBy Horizontal Stacking in PySpark Dataframe [duplicate]PySpark Dataframe中的GroupBy水平堆叠[重复]
【发布时间】:2019-07-18 12:48:00
【问题描述】:

我有一个这样的 PySpark 数据框:

cust_id prod
      1    A
      1    B
      1    C
      2    D
      2    E
      2    F

期望的输出:

cust_id   prod
      1  A/B/C
      2  D/E/F

现在使用 Pandas 我可以像下面这样:

T=df.groupby(['cust_id'])['prod'].apply(lambda x:np.hstack(x)).reset_index()

def func_x(ls):
    n=len(ls)
    s=''
    for i in range(n):
        if n-i==1:
            s=s+ls[i]
        else:
            s=s+ls[i]+'/'
    return s

T['prod1']=T['prod'].apply(lambda x:func_x(x))

此代码在 PySpark 中的等效项是什么?

【问题讨论】:

  • 你需要使用collect_listconcat_wsdf.groupBy("cust_id").agg(concat_ws("/", collect_list("prod"))) 之类的东西 - 让我找个骗子

标签: group-by pyspark stack transpose


【解决方案1】:
import pyspark.sql.functions as F
separator = '/'
T = df.groupby('cust_id').agg(F.concat_ws(separator, f.collect_list(df.col2)))

【讨论】:

    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多