gar*_*ong 0 scala apache-spark apache-spark-sql
表1 --Spark DataFrame表
表1中有一个名为"productMe"的栏目; 还有其他列,如a,b,c等,其架构名称包含在架构数组T中.
我想要的是架构数组T中的列的内积(产品中每列的两列)和列productMe(表2).并总结表2的每列以得到表3.
如果您有充分的理由在一步中获得表3,则表2不是必需的.
表2 - 内部产品表
例如,列"a·productMe"为(3*0.2,6*0.6,5*0.4)得到(0.6,3.6,2)
表3 - 总和表
例如,列"sum(a·productMe)"是0.6 + 3.6 + 2 = 6.2.
表1是Spark的DataFrame,我该如何获得表3?
您可以尝试以下内容:
val df = Seq(
(3,0.2,0.5,0.4),
(6,0.6,0.3,0.1),
(5,0.4,0.6,0.5)).toDF("productMe", "a", "b", "c")
import org.apache.spark.sql.functions.col
val columnsToSum = df.
columns. // <-- grab all the columns by their name
tail. // <-- skip productMe
map(col). // <-- create Column objects
map(c => round(sum(c * col("productMe")), 3).as(s"sum_${c}_productMe"))
val df2 = df.select(columnsToSum: _*)
df2.show()
# +---------------+---------------+---------------+
# |sum_a_productMe|sum_b_productMe|sum_c_productMe|
# +---------------+---------------+---------------+
# | 6.2| 6.3| 4.3|
# +---------------+---------------+---------------+
Run Code Online (Sandbox Code Playgroud)
诀窍是使用df.select(columnsToSum: _*)这意味着你想要选择列的总和乘以productMe列的所有列.这:_*是一个特定于Scala的语法,用于指定我们传递重复的参数,因为我们没有固定数量的参数.
| 归档时间: |
|
| 查看次数: |
1692 次 |
| 最近记录: |