【问题标题】:Spark DF create Seq column in witcolumnSpark DF 在 witcolumn 中创建 Seq 列
【发布时间】:2021-01-15 19:19:41
【问题描述】:

我有一个 df:

col1 col2
1 abcdefghi
2 qwertyuio

我想重复每一行,将 col2 分成 3 个长度为 3 的子字符串:

col1 col2
1 abcdefghi
1 abc
1 def
1 ghi
2 qwertyuio
2 qwe
2 rty
2 uio

我试图创建一个包含 Seq 的新列 Seq((col("col1"), substring(col("col2"),0,3))...)

    val df1 = df.withColumn("col3", Seq(
(col("col1"), substring(col("col2"),0,3)),
(col("col1"), substring(col("col2"),3,3)),
(col("col1"), substring(col("col2"),6,3)) ))

我的想法是选择那个新列,并减少它,得到一个最终的 Seq。然后将其传递给 DF 并将其附加到初始 df。

我在 withColumn 中遇到错误,例如:

Exception in thread "main" java.lang.RuntimeException: Unsupported literal type class scala.collection.immutable.$colon$colon

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    您可以改用 Spark 数组函数:

    val df1 = df.union(
        df.select(
            $"col1",
            explode(array(
                substring(col("col2"),0,3),
                substring(col("col2"),3,3),
                substring(col("col2"),6,3)
           )).as("col2")
        )
    )
    
    df1.show
    +----+---------+
    |col1|     col2|
    +----+---------+
    |   1|abcdefghi|
    |   2|qwertyuio|
    |   1|      abc|
    |   1|      cde|
    |   1|      fgh|
    |   2|      qwe|
    |   2|      ert|
    |   2|      yui|
    +----+---------+
    

    【讨论】:

      【解决方案2】:

      你也可以使用udf,

      val df = spark.sparkContext.parallelize(Seq((1L,"abcdefghi"), (2L,"qwertyuio"))).toDF("col1","col2")
      df.show(false)
      // input
      +----+---------+
      |col1|col2     |
      +----+---------+
      |1   |abcdefghi|
      |2   |qwertyuio|
      +----+---------+
       
      // udf
      val getSeq = udf((col2: String) => col2.split("(?<=\\G...)"))
      df.withColumn("col2", explode(getSeq($"col2")))
        .union(df).show(false)
      
      +----+---------+
      |col1|col2     |
      +----+---------+
      |1   |abc      |
      |1   |ghi      |
      |1   |abcdefghi|
      |1   |def      |
      |2   |qwe      |
      |2   |rty      |
      |2   |uio      |
      |2   |qwertyuio|
      +----+---------+
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-23
        • 2021-04-13
        • 2019-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多