spark scala如何将Dataframe中的整数列转换为十六进制大写字符串?

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

我们可以使用以下函数来转换单个整数值。

val x=100
Integer.toString(x, 16).toUpperCase

但是如何将它应用于整数列以生成具有十六进制字符串的新列呢?谢谢!
以下方法无效。

testDF = testDF.withColumn("data_hex_string", Integer.toString(testDF("data"), 16).toUpperCase)
bwitn5fc

bwitn5fc1#

好吧,没有spark本机函数,所以创建一个udf函数来实现这一点。

import org.apache.spark.sql.functions.udf
def toHex = udf((int: Int) => java.lang.Integer.toString(int, 16).toUpperCase)

df.withColumn("hex", toHex($"int")).show()

+---+---+---+
| id|int|hex|
+---+---+---+
|  1|  1|  1|
|  2| 11|  B|
|  3| 23| 17|
+---+---+---+
e5njpo68

e5njpo682#

正如@jxc在评论中已经提到的,使用 conv 功能:

import org.apache.spark.sql.functions.{conv, lower}
df.withColumn("hex", conv($"int_col",10,16)).show

对于那些想要小写的人,用 lower :

df.withColumn("hex", lower(conv($"int_col",10,16))).show

相关问题