How to cast a column in PySpark Azure Databricks?

Are you looking to find out how to cast a column of PySpark DataFrame using Azure Databricks cloud or maybe you are looking for a solution, to find a method to do casting in PySpark using different methods? If you are looking for any of these problem solutions, you have landed on the correct page. I will also show you how to use both PySpark and Spark SQL ways of doing the casting in Azure Databricks. I will explain it with a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to cast columns in PySpark Azure Databricks.

In this blog, I will teach you the following with practical examples:

  • Syntax of cast()
  • Casting with select() function
  • Casting with withColumn() function
  • Casting with selectExpr() function
  • Casting with SQL expression

The PySpark’s cast() function used for casting a column from one DataType to another.

Syntax:

column.cast()

What is the syntax of the cast() function in PySpark Azure Databricks?

The syntax is as follows:

column.cast(data_type)
Parameter NameRequiredDescription
data_type (str, DataType)YesIt represents the column’s new data type.
Table 1: cast() Method in PySpark Databricks Parameter list with Details

Apache Spark Official documentation link: cast()

Create a simple DataFrame

Gentle reminder:

In Databricks,

  • sparkSession made available as spark
  • sparkContext made available as sc

In case, you want to create it manually, use the below code.

from pyspark.sql.session import SparkSession

spark = SparkSession.builder 
    .master("local[*]") 
    .appName("azurelib.com") 
    .getOrCreate()

sc = spark.sparkContext

a) Create manual PySpark DataFrame

data = [
    ('1','Murciélago','Lamborghini','53566.22','2008-05-20','false'),
    ('2','S2000','Honda','47063.49','1984-01-13','false'),
    ('3','LeMans','Pontiac','35654.8','1989-04-27','true'),
    ('4','Suburban 2500','Chevrolet','44013.67','1954-01-06','false'),
    ('5','4Runner','Toyota','56891.95','1959-06-12','true')
]

columns = ["id","model","make","price","release_date","is_petrol"]
df = spark.createDataFrame(data, schema=columns)
df.printSchema()
df.show(truncate=False)

"""
root
 |-- id: string (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
 |-- price: string (nullable = true)
 |-- release_date: string (nullable = true)
 |-- is_petrol: string (nullable = true)

+---+-------------+-----------+--------+------------+---------+
|id |model        |make       |price   |release_date|is_petrol|
+---+-------------+-----------+--------+------------+---------+
|1  |Murciélago  |Lamborghini|53566.22|2008-05-20  |false    |
|2  |S2000        |Honda      |47063.49|1984-01-13  |false    |
|3  |LeMans       |Pontiac    |35654.8 |1989-04-27  |true     |
|4  |Suburban 2500|Chevrolet  |44013.67|1954-01-06  |false    |
|5  |4Runner      |Toyota     |56891.95|1959-06-12  |true     |
+---+-------------+-----------+--------+------------+---------+
"""

b) Creating a DataFrame by reading files

Download and use the below source file.

# replace the file_paths with the source file location which you have downloaded.

df_2 = spark.read.format("csv").option("header", True).load(file_path)
df_2.printSchema()

"""
root
 |-- id: string (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
 |-- price: string (nullable = true)
 |-- release_date: string (nullable = true)
 |-- is_petrol: string (nullable = true)
"""

Note: Here, I will be using the manually created DataFrame.

The PySpark DataType classes subclasses are shown below, and we can only cast DataFrame columns to these types. They were StringType, NumericType, ArrayType, MapType, BooleanType, StructType, DateType, TimestampType, NullType, ObjectType, HiveStringType, CalendarIntervalType, and BinaryType.

How to cast a column of PySpark DataFrame in Azure Databricks along with the select() function?

In this section, let’s see how to cast a column from one DataType to another using the cast() function along with the select() function. Let me provide an example.

Example:

from pyspark.sql.functions import col

df.select(
    col("id").cast("INTEGER"),
    col("price").cast("DOUBLE"),
    col("release_date").cast("DATE"),
    col("is_petrol").cast("BOOLEAN")
).printSchema()

"""
Output:

root
 |-- id: integer (nullable = true)
 |-- price: double (nullable = true)
 |-- release_date: date (nullable = true)
 |-- is_petrol: boolean (nullable = true)

"""

In this example, We have cast the columns from StringType to other DataTypes using the cast() function. We have achieved this by passing the new data type as a string value, and we can get similar results by passing pyspark.sql.types inside it. Let’s use it in the upcoming section.

How to cast a column of PySpark DataFrame in Azure Databricks along with the withColumn() function?

In this section, let’s see how to cast a column from one DataType to another using the cast() function along with the withColumn() function. Let me provide an example.

Example:

from pyspark.sql.functions import col
from pyspark.sql.types import IntegerType, DoubleType, BooleanType, DateType

df \
.withColumn("id", col("id").cast(IntegerType())) \
.withColumn("price", col("price").cast(DoubleType())) \
.withColumn("release_date", col("release_date").cast(DateType())) \
.withColumn("is_petrol", col("is_petrol").cast(BooleanType())) \
.printSchema()

"""
Output:

root
 |-- id: integer (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
 |-- price: double (nullable = true)
 |-- release_date: date (nullable = true)
 |-- is_petrol: boolean (nullable = true)

"""

In this example, We have cast the columns from StringType to other DataTypes using the cast() function. We have achieved this by passing the pyspark.sql.types as an input argument.

How to cast a column of PySpark DataFrame in Azure Databricks along with the selectExpr() function?

In this section, let’s see how to cast a column from one DataType to another using the cast() function along with the selectExpr() function. Let me provide an example.

Example:

df.selectExpr(
    "CAST(id as INTEGER)",
    "model", "make",
    "CAST(price as DOUBLE)",
    "CAST(release_date as DATE)",
    "CAST(is_petrol as BOOLEAN)"    
).printSchema()

"""
Output:

root
 |-- id: integer (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
 |-- price: double (nullable = true)
 |-- release_date: date (nullable = true)
 |-- is_petrol: boolean (nullable = true)

"""

How to cast a column of PySpark DataFrame in Azure Databricks using SQL expression?

In this section, let’s see how to cast a column from one DataType to another using the cast() function along with SQL expression. In order to perform raw SQL, we have to convert our DataFrame into SQL view, et me provide an example.

Example:

df.createOrReplaceTempView("cars")

spark.sql('''
    SELECT
        INT(id), model, make,
        DOUBLE(price),
        DATE(release_date),
        BOOLEAN(is_petrol)
    FROM cars
''').printSchema()

"""
Output:

root
 |-- id: integer (nullable = true)
 |-- model: string (nullable = true)
 |-- make: string (nullable = true)
 |-- price: double (nullable = true)
 |-- release_date: date (nullable = true)
 |-- is_petrol: boolean (nullable = true)

"""

I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.

When should you cast a column in PySpark using Azure Databricks?

These could be the possible reasons:

  1. For converting string type to int type
  2. For converting double type to int type
  3. For converting int type to string type

Real World Use Case Scenarios for casting a column in PySpark Azure Databricks?

Assume you have an employee dataset with their id, name, and salary column. But in this case, the data type of the salary column is in string type. Here we can’t perform any aggregation functions on top of the salary column. Therefore, by casting the salary column from string type to integer or double type you can perform calculations on top of it.

What are the alternatives for casting columns in PySpark using Azure Databricks?

There are multiple alternatives for casting columns in a PySpark DataFrame, which are as follows:

  • col().cast(): This is a column function that helps in casting column values from one DataType to another.
  • Using SQL expressions such as CAST(), INT(), BOOLEAN(), and so on.

Final Thoughts

In this article, we have learned about how to cast columns using different methods in PySpark Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.

Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.

Arud Seka Berne S

As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.