在pyspark中将整数列转换为字符串ip

8nuwlpux  于 2021-05-27  发布在  Spark
关注(0)|答案(2)|浏览(535)

我有一个pysparkDataframe,ipv4值是整数,我想把它们转换成字符串形式。最好没有可能对性能有很大影响的udf。
输入示例:

+---------------+
|         IP_int|
+---------------+
|       67633643|
|      839977746|
|      812147536|
+---------------+

输出示例:

+---------------+
|         IP_str|
+---------------+
|      4.8.1.235|
|    50.17.11.18|
|   48.104.99.80|
+---------------+
7tofc5zh

7tofc5zh1#

此代码将ip从整数转换为字符串:

ip_str_col = f.concat_ws(
    ".",
    ((f.col("IP_int") / 16777216).cast("int") % 256).cast("string"),
    ((f.col("IP_int") / 65536).cast("int") % 256).cast("string"),
    ((f.col("IP_int") / 256).cast("int") % 256).cast("string"),
    (f.col("IP_int").cast("int") % 256).cast("string"),
)
df = df.withColumn("IP_str", ip_str_col)
df.show()

输出:

+---------+------------+
|   IP_int|      IP_str|
+---------+------------+
| 67633643|   4.8.1.235|
|839977746| 50.17.11.18|
|812147536|48.104.99.80|
+---------+------------+
jpfvwuh4

jpfvwuh42#

你可以用 conv ,分成4块 substring ,将其转换回十进制 conv ,并与 concat_ws .

from pyspark.sql import functions as F

df = df.withColumn("hex", F.lpad(F.conv("IP_int", 10, 16), 8, "0"))

df.select(
    "IP_int",
    F.concat_ws(
        ".",
        F.conv(F.substring("hex", 1, 2), 16, 10),
        F.conv(F.substring("hex", 3, 2), 16, 10),
        F.conv(F.substring("hex", 5, 2), 16, 10),
        F.conv(F.substring("hex", 7, 2), 16, 10),
    ).alias("IP_str"),
).show()

+---------+------------+
|   IP_int|      IP_str|
+---------+------------+
| 67633643|   4.8.1.235|
|839977746| 50.17.11.18|
|812147536|48.104.99.80|
+---------+------------+

编辑:使用位移位运算符

df = df.withColumn(
    "IP_str",
    F.concat_ws(
        ".",
        (F.shiftRight("IP_int", 8*3) % 256).cast("string"),
        (F.shiftRight("IP_int", 8*2) % 256).cast("string"),
        (F.shiftRight("IP_int", 8) % 256).cast("string"),
        (F.col("IP_int") % 256).cast("string"),
    ),
)

相关问题