gpt4 book ai didi

scala - 获取数组列的大小/长度

转载 作者:行者123 更新时间:2023-12-03 04:52:45 29 4
gpt4 key购买 nike

我是 Scala 编程新手,这是我的问题:如何计算每行的字符串数量?我的数据框由一列 Array[String] 类型组成。

friendsDF: org.apache.spark.sql.DataFrame = [friends: array<string>]

最佳答案

您可以使用size功能:

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|
+-------------+
<小时/>

添加为新列:

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

关于scala - 获取数组列的大小/长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46098573/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com