我如何转换数组<FloatType>使用 Scala 在 spark 数据帧中转换为 BinaryType [英] How do I convert array<FloatType> to BinaryType in spark dataframes using Scala
问题描述
在 spark 数据框中,我的一列包含浮点值数组,如何将该列转换为 BinaryType.
In a spark data frame, one of my columns contains an Array of float values, how can I convert that column to BinaryType.
以下是一些示例数据及其外观:
Here is some sample data and how it looks:
val df = spark.sparkContext.parallelize(Seq(("one", Array[Float](1, 2, 3, 4, 5)), ("two", Array[Float](6, 7, 8, 9, 10)))).toDF("Name", "Values")
df.show()
df:org.apache.spark.sql.DataFrame
Name:string
Values:array
element:float
+----+--------------------+
|Name| Values|
+----+--------------------+
| one|[1.0, 2.0, 3.0, 4...|
| two|[6.0, 7.0, 8.0, 9...|
+----+--------------------+
在上面的例子中,Values 字段是 Array,我如何才能将 Values 字段转换为 Array/BinaryType?
In the above example, Values field is Array, How can I convert to Values field Array/BinaryType?
预期的架构是:
Name:string
Values:binary
推荐答案
你需要写一个 UDF 接受 Array[Float] 并返回 Array[Byte]
You need to write an UDF that takes Array[Float] and return Array[Byte]
val binUdf = udf((arr:WrappedArray[Float]) => {arr.to.map(_.toByte)})
scala> df.withColumn("Values",binUdf($"Values")).printSchema
root
|-- Name: string (nullable = true)
|-- Values: binary (nullable = true)
或者您可以在创建 DataFrame 时执行此操作,方法是更改 Array[Float] -> Array[Byte].
Or You can do it when creating the DataFrame, by changing Array[Float] -> Array[Byte] as well.
val df = spark.sparkContext.parallelize(Seq(("one", Array[Byte](1, 2, 3, 4, 5)), ("two", Array[Byte](6, 7, 8, 9, 10)))).toDF("Name", "Values")
这篇关于我如何转换数组<FloatType>使用 Scala 在 spark 数据帧中转换为 BinaryType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!