【问题标题】:How to conditionally remove the first two characters from a column如何有条件地从列中删除前两个字符
【发布时间】:2018-09-04 20:37:09
【问题描述】:

我有一些电话记录的以下数据,我想从每条记录中删除前两个值,因为它们是国家代码。我可以通过什么方式使用 Scala、SparkHive

phone
|917799423934|
|019331224595|
|  8981251522|
|917271767899|

我希望结果是:

phone
|7799423934|
|9331224595|
|8981251522|
|7271767899|

我们如何从每条记录或该列的每一行中删除前缀 91,01?

【问题讨论】:

  • 在 898 条目之前 / 的 是故意的吗?
  • 不是故意的

标签: scala apache-spark hadoop hive


【解决方案1】:

手机大小可以不同,可以使用这样的构造(Scala):

df.withColumn("phone", expr("substring(phone,3,length(phone)-2)"))

【讨论】:

【解决方案2】:

我相信一个改进,会更喜欢包含包含或等效的列表,但这里是:

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

case class Tel(telnum: String)
val ds = Seq(
     Tel("917799423934"),
     Tel("019331224595"),
     Tel("8981251522"),
     Tel("+4553")).toDS()

val ds2 = ds.withColumn("new_telnum", when(expr("substring(telnum,1,2)") === "91" || expr("substring(telnum,1,2)") === "01", expr("substring(telnum,3,length(telnum)-2)")).otherwise(col("telnum"))) 

ds2.show

返回:

+------------+----------+
|      telnum|new_telnum|
+------------+----------+
|917799423934|7799423934|
|019331224595|9331224595|
|  8981251522|8981251522|
|       +4553|     +4553|
+------------+----------+

我们可能需要考虑 +,但没有说明任何内容。

【讨论】:

  • 可以使用 .isin 以更简单的方式比较 91 和 01。
  • stackoverflow.com/users/6933993/thebluephantom 感谢您的帮助,它成功了。
  • 你能解释一下 substring(telnum,3,length(telnum)-2 什么是 3 @thebluephantom
  • 从第 3 个位置开始绕过字符串 01 & 91
【解决方案3】:

使用正则表达式

使用regexp_replace(必要时添加更多扩展代码):

select regexp_replace(trim(phone),'^(91|01)','') as phone --removes leading 91, 01 and all leading and trailing spaces
from table;

同样使用regexp_extract:

select regexp_extract(trim(phone),'^(91|01)?(\\d+)',2) as phone --removes leading and trailing spaces, extract numbers except first (91 or 01) 
from table;

【讨论】:

    【解决方案4】:

    如果它们是字符串,那么对于 Hive 查询:

    sql("select substring(phone,3) from table").show
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多