【问题标题】:How to extract subnet from full address from a Dataframe?如何从数据帧的完整地址中提取子网?
【发布时间】:2018-01-29 08:18:13
【问题描述】:

我创建了一个临时数据框,如下所示:

var someDF = Seq(("1","1.2.3.4"), ("2","5.26.6.3")).toDF("s/n", "ip")

有没有办法从完整的 IP 地址中提取子网并放入新列“子网”?

输出示例:

---------------------------
|s/N | ip       | subnet  |
---------------------------
|1   | 1.2.3.4  | 1.2.3.x |
|2   | 5.26.6.3 | 5.26.6.x|
---------------------------

【问题讨论】:

    标签: scala apache-spark dataframe extract subnet


    【解决方案1】:

    您可以使用UDF 来执行此操作:

    val getSubnet = udf((ip: String) => ip.split("\\.").init.mkString(".") + ".x")
    
    val df = someDF.withColumn("subnet", getSubnet($"ip"))
    

    这会给你这个数据框:

    +---+--------+--------+
    |s/n|      ip|  subnet|
    +---+--------+--------+
    |  1| 1.2.3.4| 1.2.3.x|
    |  2|5.26.6.3|5.26.6.x|
    +---+--------+--------+
    

    【讨论】:

      【解决方案2】:

      您可以通过concat_wssubstring_index inbuilt functions 实现您的要求。

      import org.apache.spark.sql.functions._
      someDF.withColumn("subnet", concat_ws(".", substring_index($"ip", ".", 3), lit("x")))
      

      【讨论】:

        【解决方案3】:

        您可以尝试以下方法:非常简单的代码,但会提高您的性能:

        import org.apache.spark.sql.functions.{ concat, lit, col }
        
        someDF.withColumn("subnet", concat(regexp_replace(col("ip"), "(.*\\.)\\d+$", "$1"), lit("x"))).show()
        

        Output

        +---+--------+--------+
        |s/n|      ip|  subnet|
        +---+--------+--------+
        |  1| 1.2.3.4| 1.2.3.x|
        |  2|5.26.6.3|5.26.6.x|
        +---+--------+--------+
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-13
          • 1970-01-01
          • 2018-04-19
          • 1970-01-01
          • 2016-04-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多