【问题标题】:How to explode each row that is an Array into columns in Spark (Scala)?如何将作为数组的每一行分解为 Spark(Scala)中的列?
【发布时间】:2021-10-01 07:19:12
【问题描述】:

我有一个带有单列“值”的 Spark DataFrame,其中每一行都是一个长度相等的数组。如何将这个单一的“值”列分解为多个列,遵循这样的模式?

Single-column DataFrame

val bronzeDfSchema = new StructType()
  .add("DATE", IntegerType)
  .add("NUMARTS", IntegerType)
  .add("COUNTS", StringType)
  .add("THEMES", StringType)
  .add("LOCATIONS", StringType)
  .add("PERSONS", StringType)
  .add("ORGANIZATIONS", StringType)
  .add("TONE", StringType)
  .add("CAMEOEVENTIDS", StringType)
  .add("SOURCES", StringType)
  .add("SOURCEURLS", StringType)

谢谢!

【问题讨论】:

    标签: scala dataframe apache-spark etl


    【解决方案1】:

    这应该可以正常工作

    val schema=Seq(("DATE",0),("NUMARTS",1),("COUNTS",2),("THEMES",3),("LOCATIONS",4),("PERSONS",5),("ORGANIZATIONS",6),("TONE",7),("CAMEOEVENTIDS",8),("SOURCES",9),("SOURCEURLS",10))
    
    val df2=schema.foldLeft(df)((df,x)=>df.withColumn(x._1,col("value").getItem(x._2)))
    

    完成此操作后,只需将该列转换为所需的数据类型即可。

    【讨论】:

    • 谢谢,这行得通!我对 Scala 还很陌生,所以 x._1 是什么意思?它与例如有什么不同? x(0)?
    • 欢迎,它是元组的第一个元素。
    • @viethungha0610:考虑accepting 将您的问题标记为已解决的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2020-12-06
    • 1970-01-01
    • 2021-02-24
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多