根据条件创建一列并继承先前的值

时间:2020-02-23 14:24:33

标签: apache-spark pyspark apache-spark-sql pyspark-sql pyspark-dataframes

我有下面的数据框,该数据框由“ col1”排序。

+----+----+
|col1|col2|
+----+----+
|   a|   x|
|   a|   x|
|   a|   y|
|   b|   x|
|   b|   z|
|   c|   x|
|   c|   y|
|   d|   z|
|   d|   x|
+----+----+

我想添加一个新列“ col3”,即对于“ col1”中唯一组(“ a”,“ b”,“ c”,“ d”)中的每一行,如果“ col2”值in('x'或'y')将值加1,否则如果值是'z'或任何其他值继承该值。例如,在第一行中,由于col2为x,因此我们通过加0 + 1 = 1来增加1;在第二行中,由于col2再次为x,我们将增加1 +1 = 2,依此类推。对于第二组,其中col1值为b(第4行),我们从new开始,由于col2值为x,因此我们递增0 + 1 =1。在第5行中,由于col2值为z,因此我们不递增并采用先前的值,即1 在“ d”的情况下(第8行)。由于col2值不在x或y中,因此我们不递增并将其保留为0。

+----+----+----+
|col1|col2|col3|
+----+----+----+
|   a|   x|   1|
|   a|   x|   2|
|   a|   y|   3|
|   b|   x|   1|
|   b|   z|   1|
|   c|   x|   1|
|   c|   y|   2|
|   d|   z|   0|
|   d|   x|   1|
+----+----+----+

无论如何,我无需在pyspark中使用UDF即可实现这一目标

1 个答案:

答案 0 :(得分:4)

使用窗口对There are three kinds of directives in Angular: Components—directives with a template. Structural directives—change the DOM layout by adding and removing DOM elements. Attribute directives—change the appearance or behavior of an element, component, or another directive 进行分区,然后使用条件表达式创建新列。

col1

代码的结果正是您想要的。

from pyspark.sql.functions import *
from pyspark.sql import Window

w = Window.partitionBy("col1").rowsBetween(Window.unboundedPreceding, Window.currentRow)
df.withColumn("col3", sum(when(col("col2").isin("x", "y"), 1).otherwise(0)).over(w)).orderBy("col1").show(10)
相关问题