PySpark lag() Function
The function that allows the user to query on more than one row of a table returning the previous row in the table is known as lag in Python. Apart from returning the offset value, the lag function also gives us the feature to set the default value in spite of None in the column. The setting of the default value is optional but it proves to b useful numerous times. In this article, we will discuss regarding the same, i.e., setting the default value for pyspark.sql.functions.lag to a value within the current row.
Syntax: pyspark.sql.functions.lag(data_frame[‘lag_column’], lag_value, ‘default_value’)
- lag_column: It is the column on which lag has to be done.
- lag_value: It is the value by which lag has to be performed on the particular column.
- default_value: It is the value that needs to be set inspite of None in the column.
In this example, we created the data frame which has 3 columns ‘Serial_Number‘, ‘Brand‘ and ‘Model‘ as follows:
Then, partition using the Window function on the Brand column and lag on the column Brand by 1 using lag function and set the default value ‘Any Other Brand‘ for rest of the cases.
In this example, we have used a data set (link), which is basically a 5×5 data frame as follows:
Then, partition on age, class and fees columns using the Window function and lag on the column subject by 1 using the lag function and set the default value ‘Same Subject‘ for rest of the cases.
Please Login to comment...