我有一个带有小数列的 Spark 数据框。我想将此列转换为二进制字符串。有什么功能可以帮助任何人吗?
谢谢!
有一个bin 内置函数 说明
An expression that returns the string representation of the binary value of the given long column. For example, bin("12") returns "1100".
所以如果你有一个数据框
+-----+
|Value|
+-----+
|4 |
+-----+
root
|-- Value: decimal(10,0) (nullable = true)
您可以将bin
功能用作
import org.apache.spark.sql.functions._
data.withColumn("Value_Binary", bin(col("Value")))
这应该给你
+-----+------------+
|Value|Value_Binary|
+-----+------------+
|4 |100 |
+-----+------------+
root
|-- Value: decimal(10,0) (nullable = true)
|-- Binary_value: string (nullable = true)
我通过创建用户定义的函数解决了这个问题。
val toBinStr: Int => String = _.toBinaryString
import org.apache.spark.sql.functions.udf
val toBinStrUDF = udf(toBinStr)
// Apply the UDF to change the source dataset
data.withColumn("Value_Binary", toBinStrUDF($"Value")).show