Reputation: 533
Please help me in this I am new to spark. Below is mydataframe
type col1 col2 col3
1 0 41 0
1 27 0 0
1 1 0 0
1 183 0 2
2 null 0 0
2 null 10 0
3 0 126 0
3 2 0 1
3 4 0 0
3 5 0 0
Below should be my output
type col1 col2 col3 result
1 0 41 0 0
1 27 0 0 14
1 1 0 0 13
1 183 0 2 -168
2 null 0 0
2 null 10 0
3 0 126 0 0
3 2 0 1 125
3 4 0 0 121
3 5 0 0 116
The challenge is this has to be done for every group of type column the formula is like prev(col2)-col1+col3
I tried to use window and lag function on col2 to populate result column but it did not work.
Below was my code
part = Window().partitionBy().orderBy('type')
DF = DF.withColumn('result',lag("col2").over(w)-DF.col1+DF.col3)
Now I am struggling to try with map function please help
Upvotes: 1
Views: 3742
Reputation: 41957
The logic is a bit tricky and complex.
You can do the following in pyspark
pyspark
from pyspark.sql import functions as F
from pyspark.sql import Window
import sys
windowSpec = Window.partitionBy("type").orderBy("type")
df = df.withColumn('result', F.lag(df.col2, 1).over(windowSpec) - df.col1 + df.col3)
df = df.withColumn('result', F.when(df.result.isNull(), F.lit(0)).otherwise(df.result))
df = df.withColumn('result', F.sum(df.result).over(windowSpec.rowsBetween(-sys.maxsize, -1)) + df.result)
df = df.withColumn('result', F.when(df.result.isNull(), F.lit(0)).otherwise(df.result))
scala
import org.apache.spark.sql.expressions._
import org.apache.spark.sql.functions._
val windowSpec = Window.partitionBy("type").orderBy("type")
df.withColumn("result", lag("col2", 1).over(windowSpec) - $"col1"+$"col3")
.withColumn("result", when($"result".isNull, lit(0)).otherwise($"result"))
.withColumn("result", sum("result").over(windowSpec.rowsBetween(Long.MinValue, -1)) +$"result")
.withColumn("result", when($"result".isNull, lit(0)).otherwise($"result"))
You should have the following result.
+----+----+----+----+------+
|type|col1|col2|col3|result|
+----+----+----+----+------+
|1 |0 |41 |0 |0.0 |
|1 |27 |0 |0 |14.0 |
|1 |1 |0 |0 |13.0 |
|1 |183 |0 |2 |-168.0|
|3 |0 |126 |0 |0.0 |
|3 |2 |0 |1 |125.0 |
|3 |4 |0 |0 |121.0 |
|3 |5 |0 |0 |116.0 |
|2 |null|0 |0 |0.0 |
|2 |null|10 |0 |0.0 |
+----+----+----+----+------+
Edited
the first withColumn
applies the formula prev(col2) - col1 + col3
. The second withColumn
changes null to 0 for result
column. The third withColumn
is for cumulative sum i.e. adding all the values until the current row of result column. so the three withColumn
is equivalent to prev(col2) + prev(results) 1 col1 + col3
. The last withColumn
is changing the null values to 0 in result
column.
Upvotes: 3