1

I have a DataFrame with 2 columns.I want to remove first array of the nested array in every record. Example :- I have a DF like this

+---+-------+--------+-----------+-------------+
|id |arrayField                                |
+---+------------------------------------------+
|1  |[[Akash,Kunal],[Sonu,Monu],[Ravi,Kishan]] |
|2  |[[Kunal, Mrinal],[Priya,Diya]]            |
|3  |[[Adi,Sadi]]                              |
+---+-------+---------+----------+-------------+

and I want my output like this:-

+---+-------+------+------+-------+
|id |arrayField                   |
+---+-----------------------------+
|1  |[[Sonu,Monu],[Ravi,Kishan]]  |
|2  |[[Priya,Diya]]               |
|3  | null                        |
+---+-------+------+------+-------+

1 Answer 1

2

From Spark-2.4 use slice function.

Example:

df.show(10,false)
/*
+------------------------+
|arrayField              |
+------------------------+
|[[A, k], [s, m], [R, k]]|
|[[k, M], [c, z]]        |
|[[A, b]]                |
+------------------------+
*/

import org.apache.spark.sql.functions._

df.withColumn("sliced",expr("slice(arrayField,2,size(arrayField))")).
withColumn("arrayField",when(size(col("sliced"))==0,lit(null)).otherwise(col("sliced"))).
drop("sliced").
show()
/*
+----------------+
|      arrayField|
+----------------+
|[[s, m], [R, k]]|
|        [[c, z]]|
|            null|
+----------------+
*/
Sign up to request clarification or add additional context in comments.

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.