问题描述
我有一个包含 500 万条记录的数据集,我需要使用提供多个 or 和条件的 startsWith()
替换列中的所有值。
此代码适用于单个条件:
df2.withColumn("Deposits",when(col("Deposits").startsWith("0"),"1.1").otherwise(col("Deposits"))).show()
我需要这样做:
df2.withColumn("Deposits",when(col("Deposits").startsWith("0"||"1"),"1.1").otherwise(col("Deposits")))
解决方法
将 rlike
与正则表达式 ^(1|0)
一起使用(以 1 或 0 开头):
df2.withColumn(
"Deposits",when(col("Deposits").rlike("^(1|0)"),"1.1").otherwise(col("Deposits"))
).show
如果你想根据 startwith 条件更新 Deposits
列,你可以像这样链接多个 when 表达式:
val depositsCol = Seq(
("1","1.1"),("2","1.2")
).foldLeft(col("Deposits")) { case (acc,(start,value)) =>
when(col("Deposits").startsWith(start),value).otherwise(acc)
}
df2.withColumn("Deposits",depositsCol).show
,
您可以将这两个条件分开并用||
(或)组合起来:
df2.withColumn(
"Deposits",when(
col("Deposits").startsWith("0") || col("Deposits").startsWith("1"),"1.1"
).otherwise(
col("Deposits")
)
)