user13181217
user13181217

Reputation:

how to sort value before concatenate text columns in pyspark

I need help to convert below code in Pyspark code or Pyspark sql code.

df["full_name"] = df.apply(lambda x: "_".join(sorted((x["first"], x["last"]))), axis=1)

Its basically adding one new column name full_name which have to concatenate values of the columns first and last in a sorted way.

I have done below code but don't know how to apply to sort in a columns text value.

df= df.withColumn('full_name', f.concat(f.col('first'),f.lit('_'), f.col('last')))

Upvotes: 0

Views: 1085

Answers (1)

notNull
notNull

Reputation: 31490

From Spark-2.4+:

We can use array_join, array_sort functions for this case.

Example:

df.show()
#+-----+----+
#|first|last|
#+-----+----+
#|    a|   b|
#|    e|   c|
#|    d|   a|
#+-----+----+

from pyspark.sql.functions import *
#first we create array of first,last columns then apply sort and join on array
df.withColumn("full_name",array_join(array_sort(array(col("first"),col("last"))),"_")).show()
#+-----+----+---------+
#|first|last|full_name|
#+-----+----+---------+
#|    a|   b|      a_b|
#|    e|   c|      c_e|
#|    d|   a|      a_d|
#+-----+----+---------+

Upvotes: 1

Related Questions