简体   繁体   English

如何使用Scala / Spark 2.2将列添加到现有DataFrame并使用window函数在新列中添加特定行

[英]How to add a column to the existing DataFrame and using window function to add specific rows in the new column using Scala/Spark 2.2

Eg: I would like to add the quantity sold by the date. 例如:我想按日期加上售出的数量。

Date       Quantity
11/4/2017    20 
11/4/2017    23 
11/4/2017    12 
11/5/2017    18
11/5/2017    12

Output with the new Column: 输出带有新列:

Date        Quantity, New_Column
11/4/2017      20        55
11/4/2017      23        55
11/4/2017      12        55
11/5/2017      18        30
11/5/2017      12        30

Simply use sum as a window function by specifying a WindowSpec : 通过指定WindowSpec,简单地将sum用作窗口函数:

import org.apache.spark.sql.expressions.Window

df.withColumn("New_Column", sum("Quantity").over(Window.partitionBy("Date"))).show
+---------+--------+----------+
|     Date|Quantity|New_Column|
+---------+--------+----------+
|11/5/2017|      18|        30|
|11/5/2017|      12|        30|
|11/4/2017|      20|        55|
|11/4/2017|      23|        55|
|11/4/2017|      12|        55|
+---------+--------+----------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 scala 在 Spark DataFrame 中添加新行 - Add new rows in the Spark DataFrame using scala 如何基于Spark Scala中的现有列添加新列 - How add new column based on existing column in spark scala Spark Dataframe,使用其他列添加具有功能的新列 - Spark Dataframe, add new column with function using other columns 如何添加新列以触发数据框取决于multipme现有列? - how to add new column to spark dataframe depend on multipme existing column? 如何进行 groupby 排名并将其作为列添加到 spark scala 中的现有 dataframe? - How to do a groupby rank and add it as a column to existing dataframe in spark scala? 如何使用 Scala 在 DataFrame 中添加新的可为空字符串列 - How to add a new nullable String column in a DataFrame using Scala 使用 Scala 在列中删除包含特定值的 Spark DataFrame 行 - Drop rows of Spark DataFrame that contain specific value in column using Scala Spark Scala:使用另一个 dataframe 使用 function 构建新列 - Spark Scala: build a new column using a function using another dataframe 关于如何在 Scala 中使用随机值向现有 DataFrame 添加新列 - About how to add a new column to an existing DataFrame with random values in Scala 如何使用 scala 中的 withColumn function 添加可变列表作为 dataframe 的列 - How to add a mutable list as a column of a dataframe using withColumn function in scala
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM