1

Given a dataframe with a list of arrays

Schema 
|-- items: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- name: string (nullable = true)
 |    |    |-- quantity: string (nullable = true)

+-------------------------------+
|items                          |
+-------------------------------+
|[[A, 1], [B, 1], [C, 2]]       |
---------------------------------

How do i get a string:

+-------------------------------+
|items                          |
+-------------------------------+
|A, 1, B, 1, C, 2               |
---------------------------------

Tried:

df.withColumn('item_str', concat_ws(" ", col("items"))).select("item_str").show(truncate = False)

Error:

: org.apache.spark.sql.AnalysisException: cannot resolve 'concat_ws(' ', `items`)' due to data type mismatch: argument 2 requires (array<string> or string) type, however, '`items`' is of array<struct<name:string,quantity:string>> type.;;
4
  • The error tells you that you must first transform items array into a array<string> and then call concat on it Commented Mar 10, 2020 at 8:30
  • how can i convert the sub element (quantity) to string? Commented Mar 10, 2020 at 8:33
  • try using pyspark.sql.functions.flatten Commented Mar 10, 2020 at 9:37
  • @Bitswazsky i tried flatten: df.withColumn("items_flat",flatten("items")).show(False) and got error: The argument should be an array of arrays, but 'items' is of array<struct<name:string,quantity:string>> type.;; Commented Mar 10, 2020 at 10:38

2 Answers 2

2

You can achive that using a combination of transform and array_join build-in functions:

from pyspark.sql.functions import expr

df.withColumn("items", expr("array_join(transform(items, \
                                i -> concat_ws(',', i.name, i.quantity)), ',')"))

We use transform to iterate among items and transform each of them into a string of name,quantity. Then we use array_join to concatenate all the items, returned by transform, seperated by comma.

Sign up to request clarification or add additional context in comments.

Comments

-1

Explode might be useful here

import org.apache.spark.sql.functions._
df.select(explode("items")).select("col.*")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.