Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
968 views
in Technique[技术] by (71.8m points)

scala - Get the size/length of an array column

I'm new in Scala programming and this is my question: How to count the number of string for each row? My Dataframe is composed of a single column of Array[String] type.

friendsDF: org.apache.spark.sql.DataFrame = [friends: array<string>]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the size function:

val df = Seq((Array("a","b","c"), 2), (Array("a"), 4)).toDF("friends", "id")
// df: org.apache.spark.sql.DataFrame = [friends: array<string>, id: int]

df.select(size($"friends").as("no_of_friends")).show
+-------------+
|no_of_friends|
+-------------+   
|            3|
|            1|
+-------------+

To add as a new column:

df.withColumn("no_of_friends", size($"friends")).show
+---------+---+-------------+
|  friends| id|no_of_friends|
+---------+---+-------------+
|[a, b, c]|  2|            3|
|      [a]|  4|            1|
+---------+---+-------------+

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...