Dav*_*aub 1 python apache-spark pyspark
我有一个 pyspark 数据帧,其中 IPv4 值为整数,我想将它们转换为字符串形式。最好没有可能对性能产生很大影响的 UDF。
示例输入:
+---------------+
| IP_int|
+---------------+
| 67633643|
| 839977746|
| 812147536|
+---------------+
Run Code Online (Sandbox Code Playgroud)
示例输出:
+---------------+
| IP_str|
+---------------+
| 4.8.1.235|
| 50.17.11.18|
| 48.104.99.80|
+---------------+
Run Code Online (Sandbox Code Playgroud)
你用 转换成十六进制,用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|
+---------+------------+
Run Code Online (Sandbox Code Playgroud)
编辑:使用位移运算符
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"),
),
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
223 次 |
| 最近记录: |