Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 21

Creating Spark DataFrames from Diverse Sources

This lesson is built with resources from docs.databricks.com and spark.apache.org.

Hello! Welcome back to our journey into large-scale data processing with Apache Spark.

In our last lesson, we explored the high-level architecture of Spark. We saw how its master-worker design, lazy execution model using a Directed Acyclic Graph (DAG), and in-memory processing capabilities give it a significant performance and flexibility advantage over older systems like Hadoop MapReduce.

Today, we'll move from theory to practice. Our goal is to create a Spark DataFrame from various data sources (e.g., CSV, JSON). The DataFrame is the primary API you will use when working with Spark. For someone with your background in software architecture and relational databases, you can think of a DataFrame as a distributed, immutable version of a SQL table or a pandas DataFrame, designed to be manipulated across a cluster of machines. Mastering how to get data into a DataFrame is the first essential step in building any data pipeline.

What is a Spark DataFrame?

Before we start loading data, let's solidify our understanding of what a DataFrame is. It's a two-dimensional, labeled data structure with columns of potentially different types, similar to a table in a relational database. However, it comes with powerful features tailored for big data.

To understand the concept and its advantages, please read the following brief introduction.

Chapter 1: DataFrames - A view into your structured data

The official PySpark user guide, "DataFrames - A view into your structured data", provides a clear definition of a DataFrame and its key benefits.

Read the short introductory section at the beginning of the page that defines a DataFrame and lists its advantages.

As you read, note these key characteristics:

  • Distributed Computing: The data isn't on one machine; it's partitioned and spread across the executors in your Spark cluster.
  • Schema Flexibility: Unlike rigid SQL tables, DataFrames can handle evolving or semi-structured data more gracefully.
  • Optimization: As we discussed in the last lesson, operations on DataFrames are not executed immediately. They are translated by the Catalyst Optimizer into an efficient physical plan, which is then run on the cluster.

The diagram below from our last lesson shows where the DataFrame API fits within the overall Spark architecture. It's a high-level API that sits on top of the core Spark engine, allowing you to express complex transformations efficiently.

Spark SQL and DataFrame API Architecture
This diagram shows that user programs interact with the high-level DataFrame API, which then utilizes Spark's underlying Catalyst Optimizer and execution engine (built on RDDs).

The Entry Point: SparkSession

All the code examples you'll see use a variable named spark. This object is an instance of the SparkSession class and is the main entry point for all DataFrame and SQL functionality. In interactive environments like a Databricks notebook, a SparkSession object named spark is conveniently created for you when you start your cluster.


Creating DataFrames

Spark can create DataFrames from a wide variety of sources, both structured and semi-structured. The image below gives a great overview of the possibilities.

Ways to Create DataFrames in Spark from Various Data Sources
This diagram illustrates how Spark SQL can ingest data from many different sources—such as RDDs, Parquet, JSON, CSV, and relational databases—to create a unified Spark DataFrame.

We'll focus on the most common methods: creating a DataFrame from in-memory Python objects and from external files like CSV and JSON. The primary interface for this is the SparkReader, which you access through spark.read.

Let's dive into the practical examples.

Chapter 1: DataFrames - A view into your structured data

We'll now turn to the official documentation for code examples. It provides clear, concise snippets for creating DataFrames from the most common sources.

Please review the code examples under the heading "Create a DataFrame". Focus on the subsections: "From a list of dictionaries", "From a local file" (both CSV and JSON examples), and the df.show() method under "View the DataFrame". We will discuss these in more detail below.

1. From In-Memory Data

Creating a DataFrame from a Python list is useful for testing, debugging, or working with small datasets that are already in your driver program's memory.

You can use spark.createDataFrame() with a list of dictionaries, where Spark infers the schema from the keys:

# A list of dictionaries
employees = [
    {"name": "John D.", "age": 30, "department": "HR"},
    {"name": "Alice G.", "age": 25, "department": "Finance"}
]

# Create a DataFrame
df_from_dicts = spark.createDataFrame(employees)

df_from_dicts.show()
# +---+----------+-------+
# |age|department|   name|
# +---+----------+-------+
# | 30|        HR|John D.|
# | 25|   Finance|Alice G.|
# +---+----------+-------+

Alternatively, you can provide a list of lists (or tuples) and define the schema explicitly. This is a more robust approach as it enforces data types and column names, preventing potential errors from inconsistent data.

# A list of lists
data = [
    [2021, "Isabella", "MIA", "F", 1500],
    [2021, "Noah", "NYC", "M", 1800]
]

# Define the schema
schema = "Year INT, First_Name STRING, City STRING, Sex STRING, Count INT"

# Create the DataFrame
df_with_schema = spark.createDataFrame(data, schema=schema)

df_with_schema.printSchema()
# root
#  |-- Year: integer (nullable = true)
#  |-- First_Name: string (nullable = true)
#  |-- City: string (nullable = true)
#  |-- Sex: string (nullable = true)
#  |-- Count: integer (nullable = true)

2. From Files (CSV and JSON)

This is the most common way to load data into Spark. You use spark.read and specify the format. A key point for you as an architect: while the examples use local file paths, in a real-world scenario, these paths will point to a distributed file system like Amazon S3, Azure Data Lake Storage (ADLS), or HDFS.

Reading a CSV file:

# The path would typically be a URI to cloud storage, e.g., "s3a://my-bucket/data/employees.csv"
file_path = "../data/employees.csv" 

df_csv = spark.read.csv(file_path, header=True, inferSchema=True)

df_csv.show()

Two important options here:

  • header=True: Tells Spark to use the first row of the file as the column names.
  • inferSchema=True: Instructs Spark to make an extra pass over the data to figure out the data type of each column (e.g., Integer, String, Double). While convenient for exploration, this is generally not recommended for production pipelines. It can be slow and may lead to incorrect type assignments. In production, you should define the schema explicitly for reliability and performance.

Reading a JSON file:

# The path would point to distributed storage in a real application
file_path = "../data/employees.json"

df_json = spark.read.option("multiline", "true").json(file_path)

df_json.show()

The .option("multiline", "true") is necessary if your JSON file contains a single JSON object that spans multiple lines. If your file is "JSON Lines" format (one complete JSON object per line), you don't need this option.

Test your understanding!

You have been given a string containing data in JSON Lines format:
data_string = '{"id": 1, "product": "Laptop"}\n{"id": 2, "product": "Mouse"}'

This string is not in a file but is available in a Python variable. How would you create a Spark DataFrame from this string?

Hint: Spark can read directly from an in-memory RDD created from the string.

Show answer

First, you would need to create an RDD from the string, then you can use spark.read.json() on that RDD.

# The raw data string
data_string = '{"id": 1, "product": "Laptop"}\n{"id": 2, "product": "Mouse"}'

# 1. Create an RDD from the string, splitting it by newline characters
rdd = spark.sparkContext.parallelize(data_string.split('\n'))

# 2. Use spark.read.json() to parse the RDD into a DataFrame
df = spark.read.json(rdd)

df.show()
# +---+-------+
# | id|product|
# +---+-------+
# |  1| Laptop|
# |  2|  Mouse|
# +---+-------+

This demonstrates the flexibility of Spark's readers—they can operate on file paths as well as distributed collections like RDDs.


Conclusion

In this lesson, you took your first practical step into Spark programming. You learned that the DataFrame is the central, high-level abstraction for working with structured data and how it relates to the underlying Spark architecture. Most importantly, you now know how to ingest data into a DataFrame from various common sources.

Key Takeaways:

  • A Spark DataFrame is a distributed, table-like data structure that provides a rich API for scalable data processing.
  • The SparkSession (usually available as spark) is the entry point for creating and working with DataFrames.
  • You can create DataFrames from in-memory Python objects using spark.createDataFrame(), which is useful for testing.
  • The most common method for loading data is spark.read.format("..."), with shortcuts like spark.read.csv() and spark.read.json() for popular file types.
  • For production workloads, explicitly defining a schema is preferable to using inferSchema=True for better performance and reliability.

Now that we know how to load data into a DataFrame, the next logical step is to learn how to manipulate it. In the next lesson, we will cover how to apply common transformations (e.g., selecting, filtering) and actions (e.g., aggregations) to DataFrames. This is where the real work of data processing begins.