有没有办法根据 Scala 数组过滤或标记行?
请记住,实际上行数要大得多。
样本数据
val clients= List(List("1", "67") ,List("2", "77") ,List("3", "56"),List("4","90")).map(x =>(x(0), x(1)))
val df = clients.toDF("soc","ages")
+---+----+
|soc|ages|
+---+----+
| 1| 67|
| 2| 77|
| 3| 56|
| 4| 90|
| ..| ..|
+---+----+
我想过滤 Scala 数组中的所有年龄,假设
var z = Array(90, 56,67).
df.where(($"ages" IN z)
或
df..withColumn("flag", when($"ages" >= 30 , 1)
.otherwise(when($"ages" <= 5, 2)
.otherwise(3))
最佳答案
您还可以通过对数组使用 _*
运算符将每个元素作为 arg 传递。
然后写一个案例否则使用isin
例如:
val df1 = Seq((1, 67), (2, 77), (3, 56), (4, 90)).toDF("soc", "ages")
val z = Array(90, 56,67)
df1.withColumn("flag",
when('ages.isin(z: _*), "in Z array")
.otherwise("not in Z array"))
.show(false)
+---+----+--------------+
|soc|ages|flag |
+---+----+--------------+
|1 |67 |in Z array |
|2 |77 |not in Z array|
|3 |56 |in Z array |
|4 |90 |in Z array |
+---+----+--------------+
关于scala - 基于 Scala 数组过滤或标记行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855586/