
sqrt()
The sqrt()
function calculates the square root of each numeric value in a column. It's important to note that the function operates on non-negative values.
Create Spark Session and sample DataFrame
from pyspark.sql import SparkSessionfrom pyspark.sql.functions import sqrt
# Initialize Spark Sessionspark = SparkSession.builder.appName("sqrtExample").getOrCreate()
# Sample DataFramedata = [(4.0,), (16.0,), (25.0,)]columns = ["Value"]df = spark.createDataFrame(data, columns)df.show()
Output:
+-----+
|Value|
+-----+
| 4.0|
| 16.0|
| 25.0|
+-----+
Example: Use sqrt()
to compute square root of values
sqrt("Value")
: it computes the square root of values in the Value column of the df DataFrame.alias("Square Root")
: it renames the resulting column as Square Root.
sqrt_df = df.select(sqrt("Value").alias("Square Root"))sqrt_df.show()
Output:
+-----------+
|Square Root|
+-----------+
| 2.0|
| 4.0|
| 5.0|
+-----------+
# Stop the Spark Sessionspark.stop()