python—将列(变量)列表连接到一个新的列dataframe pyspark中

8fsztsew  于 2021-05-27  发布在  Spark
关注(0)|答案(2)|浏览(316)

我使用的是pyspark,我有一个Dataframedf\u001,其中包含n列“rec”、“id”和“name”。
例如,如果我想添加一个新列'unq\u id',它将连接'rec'和'id'。当我这么做的时候,它工作得很好:

df_f_final = df_001.withColumn('unq_id', sf.concat(sf.col('rec'), sf.lit('||'), sf.col('id'))) .

但是我需要列的列表来连接dynamique(例如list):我怎么做呢?例如,create list:ll=['rec','id','name']或ll=['rec','name']并使用它生成Dataframedf\u f\u final并连接列表ll中的列
我想这很容易,但它让我发疯
谢谢你的帮助

kmpatx3s

kmpatx3s1#

看看这个,如果有用就告诉我。


# InputDF

    # +------+------+
    # |rec_id|  name|
    # +------+------+
    # |    a1| ricky|
    # |    b1|sachin|
    # +------+------+

    LL = ['rec_id', 'name']

    df1 = df.withColumn("unq_id_value", F.concat( *[F.concat(F.col(col),F.lit("||")) for col in LL]))

    df2 = df1.withColumn("unq_id_value",F.expr("substring(unq_id_value, 1, length(unq_id_value)-2)"))

    df2.show()

    # +------+------+------------+
    # |rec_id|  name|unq_id_value|
    # +------+------+------------+
    # |    a1| ricky|   a1||ricky|
    # |    b1|sachin|  b1||sachin|
    # +------+------+------------+
u91tlkcl

u91tlkcl2#

谢谢你的回答,洛卡,我终于找到了一个解决办法,和你的差不多。我做到了,而且成功了

cols = ['col1', lit('||'), 'col2', lit('||'), 'col3']
unq_id = sf.udf(lambda cols: "".join([x for x in cols]), StringType())
df.withColumn('unqid', unq_id(sf.array(cols))).show()

相关问题