Scala - 将具有逗号分隔数字(当前为字符串)的列转换为 Dataframe 中的双精度数组
Scala - Convert column having comma separated numbers (currently string) to Array of Double in Dataframe
我在 DataFrame 中有一列当前为字符串格式,具有多个逗号分隔的双数据类型值(主要是 2 或 3)。请参阅下面的架构快照。
Sample : "619.619620621622, 123.12412512699"
root
|-- MyCol: string (nullable = true)
我想将它转换为一个双精度数组,它应该如下图所示。
Desired : array<double>
[619.619620621622, 123.12412512699]
root
|-- MyCol: array (nullable = true)
| |-- element_value: double (containsNull = true)
我知道如何对单个字符串值执行此操作。现在我想在完整的 DataFrame 列上使用它。
有什么方法可以使用单/双衬代码来完成吗?
假设起点:
val spark: SparkSession = ???
import spark.implicits._
val df: DataFrame = ???
这里有一个基于UDF的解决方案:
import org.apache.spark.sql.functions._
def toDoubles: UserDefinedFunction =
udf { string: String =>
string
.split(",")
.map(_.trim) //based on your input you may need to trim the strings
.map(_.toDouble)
}
df
.select(toDoubles($"MyCol") as "doubles")
编辑:toDouble
转换已经修剪了字符串
split
+ cast
应该做的工作:
import org.apache.spark.sql.functions.{col, split}
val df = Seq(("619.619620621622, 123.12412512699")).toDF("MyCol")
val df2 = df.withColumn("myCol", split(col("MyCol"), ",").cast("array<double>"))
df2.printSchema
//root
// |-- myCol: array (nullable = true)
// | |-- element: double (containsNull = true)
我在 DataFrame 中有一列当前为字符串格式,具有多个逗号分隔的双数据类型值(主要是 2 或 3)。请参阅下面的架构快照。
Sample : "619.619620621622, 123.12412512699"
root
|-- MyCol: string (nullable = true)
我想将它转换为一个双精度数组,它应该如下图所示。
Desired : array<double>
[619.619620621622, 123.12412512699]
root
|-- MyCol: array (nullable = true)
| |-- element_value: double (containsNull = true)
我知道如何对单个字符串值执行此操作。现在我想在完整的 DataFrame 列上使用它。
有什么方法可以使用单/双衬代码来完成吗?
假设起点:
val spark: SparkSession = ???
import spark.implicits._
val df: DataFrame = ???
这里有一个基于UDF的解决方案:
import org.apache.spark.sql.functions._
def toDoubles: UserDefinedFunction =
udf { string: String =>
string
.split(",")
.map(_.trim) //based on your input you may need to trim the strings
.map(_.toDouble)
}
df
.select(toDoubles($"MyCol") as "doubles")
编辑:toDouble
转换已经修剪了字符串
split
+ cast
应该做的工作:
import org.apache.spark.sql.functions.{col, split}
val df = Seq(("619.619620621622, 123.12412512699")).toDF("MyCol")
val df2 = df.withColumn("myCol", split(col("MyCol"), ",").cast("array<double>"))
df2.printSchema
//root
// |-- myCol: array (nullable = true)
// | |-- element: double (containsNull = true)