【问题标题】:How do i transfer a string that starts with the specified character into another column in sparksql如何将以指定字符开头的字符串传输到 sparksql 中的另一列
【发布时间】:2021-12-30 05:17:16
【问题描述】:

给定下面的数据框:

Row|Address                                                                 |Contact      |
+---+------------------------------------------------------------------------+-------------+
|1  |J. Borja cor. Guillermo St., Cagayan de Oro City 08822 722-922 / 726-667|null         |
|2  |Cruz Taal cor. Apolinar Velez St.,Cagayan de Oro City 08822 725-301     |null         |
|3  |R.N. Abejuela St., Cagayan de Oro City                                  |08822 727-864|

我如何将它转换成这个:

Row|Address                                                      |Contact                  |
+---+------------------------------------------------------------------------+-------------+
|1  |J. Borja cor. Guillermo St., Cagayan de Oro City            | 08822 722-922 / 726-667 |
|2  |Cruz Taal cor. Apolinar Velez St.,Cagayan de Oro City       |           08822 725-301 |
|3  |R.N. Abejuela St., Cagayan de Oro City                      |           08822 727-864 |

【问题讨论】:

    标签: sql pyspark apache-spark-sql


    【解决方案1】:

    先用正则表达式从Address中提取Contact_tmp,然后从Address中擦除,最后用coalesce函数合并ContactContact_tmp

    df = df.withColumn('Contact_tmp', F.regexp_extract('Address', '\\d+\\s+\\d+-\\d+\\s*/*\\s*\\d*-*\\d*', 0)).select(
        'Row',
        F.expr('replace(Address, Contact_tmp, "")').alias('Address'),
        F.coalesce('Contact', 'Contact_tmp').alias('Contact')
    )
    df.show(truncate=False)
    

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      相关资源
      最近更新 更多