![]() |
VOOZH | about |
In this article, we are going to see how to add a constant column in a PySpark Dataframe.
It can be done in these ways:
Creating Dataframe for demonstration:
Output:
π ImageIn these methods, we will use the lit() function, Here we can add the constant column βliteral_values_1β with value 1 by Using the select method. The lit() function will insert constant values to all the rows. We will use withColumn() select the dataframe:
Syntax: df.withColumn("NEW_COL", lit(VALUE))
Example 1: Adding constant value in columns.
Output:
π ImageExample 2: Adding constant value based on another column.
Output:
π ImageHere we will use sql query inside the Pyspark, We will create a temp view of the table with the help of createTempView() and the life of this temp is up to the life of the sparkSession. registerTempTable() will create the temp table if it is not available or if it is available then replace it.
Then after creating the table select the table by SQL clause which will take all the values as a string.