【发布时间】:2018-08-23 09:00:33
【问题描述】:
我的输入数据中有一组列,我基于多个列在这些列上进行透视。
旋转完成后,我遇到了列标题问题。
输入数据
我的方法生成的输出 -
预期的输出标题:
我需要输出的标题看起来像 -
到目前为止完成的步骤以实现我得到的输出 -
// *Load the data*
scala> val input_data =spark.read.option("header","true").option("inferschema","true").option("delimiter","\t").csv("s3://mybucket/data.tsv")
// *Filter the data where residentFlag column = T*
scala> val filtered_data = input_data.select("numericID","age","salary","gender","residentFlag").filter($"residentFlag".contains("T"))
// *Now we will the pivot the filtered data by each column*
scala> val pivotByAge = filtered_data.groupBy("age","numericID").pivot("age").agg(expr("coalesce(first(numericID),'-')")).drop("age")
// *Pivot the data by the second column named "salary"*
scala> val pivotBySalary = filtered_data.groupBy("salary","numericID").pivot("salary").agg(expr("coalesce(first(numericID),'-')")).drop("salary")
// *Join the above two dataframes based on the numericID*
scala> val intermediateDf = pivotByAge.join(pivotBySalary,"numericID")
// *Now pivot the filtered data on Step 2 on the third column named Gender*
scala> val pivotByGender = filtered_data.groupBy("gender","numericID").pivot("gender").agg(expr("coalesce(first(numericID),'-')")).drop("gender")
// *Join the above dataframe with the intermediateDf*
scala> val outputDF= pivotByGender.join(intermediateDf ,"numericID")
如何重命名旋转后生成的列?
对于基于多列(近 300 列)透视数据集,我可以采取其他方法吗?
任何优化/提高性能的建议?
【问题讨论】:
-
当您使用 scala 时,是否有理由将其标记为 pyspark?
-
这是因为可能有人在使用 pySpark 时遇到了类似的问题。这是火花问题,而不是特定于语言的问题。此外,关于优化问题还有第二部分,因此该问题在所有 Spark 执行环境中都变得通用。
-
好的,你试过
df.withColumnRenamed吗? -
如您所见,目前最终输出大约有 10 列,因此 withColumnRenamed 可以在这里工作。但是,它不起作用有两个原因 1. 我不想通过查看生成的标题来手动重命名列的额外步骤 2. 实际上,输入文件将有 300 列,因此会发生旋转,所以它不会使用 withColumnRenamed 是可行的,因为我不会提前知道标题。寻找一种方法,我可以使用输入列名称进行透视,然后以某种方式将其附加到从该列生成的标题中
标签: scala hadoop apache-spark pyspark