如何从 Dataframe 的完整地址中提取子网?

How to extract subnet from full address from a Dataframe?

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

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

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

输出示例:

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

您可以使用 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|
+---+--------+--------+

您可以使用 concat_wssubstring_index inbuilt functions 来实现您的要求。

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

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

import org.apache.spark.sql.functions.{ concat, lit, col }

someDF.withColumn("subnet", concat(regexp_replace(col("ip"), "(.*\.)\d+$", ""), 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|
+---+--------+--------+