Featured Article

Master PySpark in Google Colab Your Ultimate Guide

Kenneth Jul 13, 2026

Spark is a powerful distributed computing framework, and Google Colab is a fantastic platform to harness this power. PySpark, the Python packaging of Apache Spark, allows data scientists and analysts to process big data with ease. By combining these three, you can run PySpark on Google Colab, enabling you to leverage cloud resources for free. Let's dive into how to set up and use PySpark on Google Colab.

the logo for pyspark colab, which has been designed to look like it is
the logo for pyspark colab, which has been designed to look like it is

Before we start, ensure you have a Google account and understand the basics of Google Colab, Python, and PySpark. This guide assumes you're already familiar with these tools, and you're ready to integrate them into a seamless data processing pipeline.

How to Use Google Colab with Python
How to Use Google Colab with Python

Setting Up PySpark on Google Colab

Google Colab provides a simple interface to set up PySpark. You can use the magic commands %pip and ! to install Python packages and run shell commands, respectively.

Google Colab Python - Tpoint Tech
Google Colab Python - Tpoint Tech

The first step is to install the PySpark package. Run the following code in a cell:

```python !apt-get install openjdk-8-jdk !pip install -q findspark !pip install -q pyspark findspark.init() from pyspark.sql import SparkSession ```

Installing Java and setting up SparkSession

🚀 Why Every Data Analyst & ML Enthusiast Should Know Google Colab
🚀 Why Every Data Analyst & ML Enthusiast Should Know Google Colab

Apache Spark requires Java to run. You'll first need to install Java using the apt-get command. After installing Java, you can initialize SparkSession to start using PySpark.

It's crucial to set up SparkSession correctly to avoid running into errors later. Ensure you provide the correct paths to Spark and Hadoop configuration files.

Setting up Spark and Hadoop variables

Complete Google Colab Beginners Guide for 2024 (video)
Complete Google Colab Beginners Guide for 2024 (video)

To set Spark and Hadoop environment variables, you can use the following code:

```python import os os.environ['SPARK_HOME'] = '/usr/local/spark' os.environ['HADOOP_HOME'] = '/usr/local/hadoop' ```

After setting up these variables, you're ready to start using PySpark on Google Colab.

Running PySpark on Google Colab

three circles with the words dataframes and rdds
three circles with the words dataframes and rdds

Now that PySpark is set up, let's explore some of its features and how to use them on Google Colab.

Start by creating a SparkSession and loading a dataset. For this example, let's use the popular Iris dataset:

How to load datasets on Google Colab
How to load datasets on Google Colab
Jupyter Notebook to PDF on Google Colab in just a few lines
Jupyter Notebook to PDF on Google Colab in just a few lines
the google logo is shown in an abstract tunnel with blue and yellow lines going through it
the google logo is shown in an abstract tunnel with blue and yellow lines going through it
two people are standing in front of a google sign at an office building with colorful swirls painted on the wall
two people are standing in front of a google sign at an office building with colorful swirls painted on the wall
Data Engineering Masterclass for Beginners
Data Engineering Masterclass for Beginners
the google logo is shown in this screenshot from an official web page for college
the google logo is shown in this screenshot from an official web page for college
Google Developer Groups
Google Developer Groups
Google's Broad Core Updates Are Global
Google's Broad Core Updates Are Global
an image of a computer screen with many numbers on it
an image of a computer screen with many numbers on it

```python spark = SparkSession.builder.appName('PySpark on Google Colab').getOrCreate() data = spark.read.csv('https://s3.amazonaws.com/assets.datacamp.com/course_files/676/Iris.csv', inferSchema=True, header=True) ```

DataFrames and SQL

PySpark comes with a DataFrame API, allowing you to manipulate data similar to pandas DataFrames. Additionally, you can run SQL queries on DataFrames using SparkSession's sql() method.

Let's examine the data, select specific columns, and filter the DataFrame using SQL:

```python # Display the first 5 rows data.show(5) # Select specific columns and filter the DataFrame using SQL df = data.select("SepalLength", "PetalLength").where(col("PetalLength") > 1.0) df.createOrReplaceTempView('iris') results = spark.sql('SELECT * FROM iris') results.show() ```

Using MLlib for machine learning

MLlib is a distributed machine learning library included with Spark. PySpark allows you to access MLlib for building and evaluating machine learning models. For this example, let's create a simple linear regression model using the Iris dataset:

```python from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler from pyspark.sql.functions import col # Select features and labels features = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth'] label = 'Species' # Prepare features and labels assembler = VectorAssembler(inputCols=features, outputCol='features') data = assembler.transform(data) # Split the data randomly into training and testing sets (30% for testing) train_data, test_data = data.randomSplit([0.7, 0.3]) # Create a LogisticRegression object lr = LogisticRegression(maxIter=10, regParam=0.01) model = lr.fit(train_data) # Make predictions on test data using the transform() method predictions = model.transform(test_data) # Show the selected columns selected_data = predictions.select("predictedLabel", col(label).alias("trueLabel")) selected_data.show() ```