简体   繁体   English

将 Stringtype 转换为 ArrayType

[英]Cast Stringtype to ArrayType

Is it possible to cast a StringType column to an ArrayType column in a spark dataframe ?是否可以将 StringType 列转换为 spark 数据框中的 ArrayType 列?

df.printSchema() gives this df.printSchema()给出了这个

Schema ->架构 ->
a: string(nullable= true)一个:字符串(可为空=真)

Now I want to convert this to现在我想将其转换为

a: array(nullable= true) a:数组(可为空=真)

As elisiah commented you have to split your string.正如Elisiah评论的那样,您必须拆分字符串。 You can use UDF:您可以使用 UDF:

    df.printSchema

    import org.apache.spark.sql.functions._

    val toArray = udf[Array[String], String]( _.split(" "))
    val featureDf = df
      .withColumn("a", toArray(df("a")))  

    featureDF.printSchema

Gives output:给出输出:

root  
 |-- a: string (nullable = true)

root
 |-- a: array (nullable = true)
 |    |-- element: string (containsNull = true)

简单地将任何column包装在functions.array另一种选择。

df.withColumn("a", functions.array(col("a")))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spark 2.0.1:将JSON数组列拆分为ArrayType(StringType) - Spark 2.0.1: split JSON Array Column into ArrayType(StringType) ScalaTestFailureLocation预期的StructField(value1,ArrayType(StringType,true),false)实际的StructField(val2,ArrayType(StringType,true),true) - ScalaTestFailureLocation Expected StructField(value1,ArrayType(StringType,true),false) Actual StructField(val2,ArrayType(StringType,true),true) 转换错误:将 ArrayType(DoubleType,true) 转换为 DoubleType - cast error :cast ArrayType(DoubleType,true) to DoubleType 输入类型必须是字符串类型,但使用Scala在Spark中得到ArrayType(StringType,true)错误 - Input type must be string type but got ArrayType(StringType,true) error in Spark using Scala 如何避免在 Spark (2.4) SQL 中自动转换 ArrayType - Scala 2.11 - How to avoid automatic cast for ArrayType in Spark (2.4) SQL - Scala 2.11 Spark:递归“ ArrayType Column => ArrayType Column”功能 - Spark: Recursive 'ArrayType Column => ArrayType Column' function 在Spark Dataframe中使用arraytype - working with arraytype in spark Dataframe 使用UDF Spark将字符串的嵌套ArrayType转换为日期的嵌套ArrayType - Converting nested ArrayType of String to Nested ArrayType of date using UDF spark 将 Spark 中的多个 ArrayType Columns 合并为一个 ArrayType Column - Combine multiple ArrayType Columns in Spark into one ArrayType Column 在Spark Scala中创建ArrayType列 - Create ArrayType column in Spark scala
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM