【问题标题】:applying function on all column spark在所有列火花上应用函数
【发布时间】:2017-03-02 14:34:53
【问题描述】:

我已经完成了这段代码,我的问题是函数转换数据类型,除了列时间戳之外,我如何同时转换数据集中包含的所有列,另一个问题是如何将函数 avg 应用于所有除列时间戳外的列。 非常感谢

val df = spark.read.option("header",true).option("inferSchema", "true").csv("C:/Users/mhattabi/Desktop/dataTest.csv")
val result=df.withColumn("new_time",((unix_timestamp(col("time")) /300).cast("long") * 300).cast("timestamp"))
result("value").cast("float")//here the first question 
val finalresult=result.groupBy("new_time").agg(avg("value")).sort("new_time")//here the second question about avg
finalresult.coalesce(1).write.format("com.databricks.spark.csv").option("header", "true").save("C:/mydata.csv")

【问题讨论】:

  • 你不能为你想转换的每一列添加withColumn吗? avg 和 agg 中的列一样多?
  • @Mariusz 数据集很大的问题,还有很多列,只想做一些除了列时间之外的所有列的事情

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


【解决方案1】:

这在 pyspark 中很容易实现,但我在尝试将其重写为 scala 代码时遇到了麻烦......我希望你能以某种方式管理它。

from pyspark.sql.functions import *
df = spark.createDataFrame([(100, "4.5", "5.6")], ["new_time", "col1", "col2"])
columns = [col(c).cast('float') if c != 'new_time' else col(c) for c in df.columns]
aggs = [avg(c) for c in df.columns if c != 'new_time']
finalresult = df.select(columns).groupBy('new_time').agg(*aggs)
finalresult.explain()

*HashAggregate(keys=[new_time#0L], functions=[avg(cast(col1#14 as double)), avg(cast(col2#15 as double))])
+- Exchange hashpartitioning(new_time#0L, 200)
   +- *HashAggregate(keys=[new_time#0L], functions=[partial_avg(cast(col1#14 as double)), partial_avg(cast(col2#15 as double))])
      +- *Project [new_time#0L, cast(col1#1 as float) AS col1#14, cast(col2#2 as float) AS col2#15]
         +- Scan ExistingRDD[new_time#0L,col1#1,col2#2]

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2018-01-16
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多