PySpark DataFrames are distributed collections of data organized into named columns. They provide an efficient way to process structured data using Apache Spark.
Initialization SparkSession
SparkSession is the entry point for creating and working with PySpark DataFrames. Initialise it before running the examples.
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("CreateDataFrame") \
.getOrCreate()
Explanation:
- SparkSession imports the required class.
- builder configures the Spark application.
- appName() assigns an application name.
- getOrCreate() creates a new session or reuses an existing one.
Syntax
spark.createDataFrame( data, schema=None, samplingRatio=None, verifySchema=True )
Parameters:
- data: The input collection, RDD, Pandas DataFrame, NumPy array, or another supported data source.
- schema: Defines column names and data types. It is optional.
- samplingRatio: Specifies the fraction of RDD records used for schema inference.
- verifySchema: Enables data-type verification against the specified schema. Its behavior has exceptions for certain Arrow-based inputs.
Methods to Create PySpark DataFrame
1. Creating a DataFrame from a List of Tuple
It can represent rows, with each tuple containing values for the corresponding columns. Pass column names through the schema parameter.
data = [
(1, "Alice"),
(2, "Bob"),
(3, "Charlie")
]
columns = ["id", "name"]
df = spark.createDataFrame(data, schema=columns)
df.show()
df.printSchema()
Output

Explanation:
- data contains three tuples representing individual rows.
- columns defines the names of the two columns.
- createDataFrame() converts the collection into a DataFrame and infers column types.
- show() displays the records, while printSchema() displays their structure.
2. Creating a DataFrame from Row Objects
Row objects represent individual records with named or positional fields. This approach is useful when working with structured Python records.
from pyspark.sql import Row
data = [
Row(id=1, name="Alice"),
Row(id=2, name="Bob"),
Row(id=3, name="Charlie")
]
df = spark.createDataFrame(data)
df.show()
df.printSchema()
Output

Explanation:
- Row creates records with named fields.
- createDataFrame() uses the field names to construct columns and infers their data types.
- This method is convenient when records already use the Row format.
3. Creating a DataFrame with an Explicit Schema
An explicit schema specifies column names and data types before creating the DataFrame. It is useful when the expected structure must remain consistent.
data = [
(1, "Alice", 25),
(2, "Bob", 30),
(3, "Charlie", 28)
]
schema = "id INT, name STRING, age INT"
df = spark.createDataFrame(data, schema=schema)
df.show()
df.printSchema()
Output

Explanation:
- schema defines three columns and their data types.
- INT represents integer values, while STRING represents text.
- Spark uses the provided schema instead of inferring these types from the data.
4. Creating a DataFrame from Pandas DataFrame
Existing Pandas DataFrames can be converted to PySpark DataFrames for Spark-based processing. This is convenient when data has already been prepared using Pandas.
import pandas as pd
pandas_df = pd.DataFrame({
"id": [1, 2, 3],
"name": ["Alice", "Bob", "Charlie"],
"age": [25, 30, 28]
})
df = spark.createDataFrame(pandas_df)
df.show()
df.printSchema()
Output

Explanation:
- pd.DataFrame() creates a DataFrame using Pandas.
- spark.createDataFrame() converts the Pandas DataFrame into a PySpark DataFrame.
- Pandas conversion may require additional memory because the Pandas data resides locally before conversion.
5. Creating DataFrame from an RDD
An existing Resilient Distributed Dataset (RDD) can be converted into a DataFrame. This method is useful when data is already represented as an RDD.
rdd = spark.sparkContext.parallelize([
(1, "Alice"),
(2, "Bob"),
(3, "Charlie")
])
df = spark.createDataFrame(
rdd,
schema=["id", "name"]
)
df.show()
df.printSchema()
Output

Explanation:
- parallelize() creates an RDD from a local collection.
- createDataFrame() converts the RDD into a DataFrame.
- schema assigns column names, while Spark infers their data types.
Creating a PySpark DataFrame form Files
PySpark provides native readers for loading CSV, text, and JSON files directly into DataFrames. These readers avoid the need to load the files into Pandas first.
6. Creating a DataFrame from a CSV FIle
CSV files contain tabular data separated by delimiters. Use spark.read.csv() to load their contents into a DataFrame. You can download csv file from, here.
df = spark.read.csv(
"employees.csv",
header=True,
inferSchema=True
)
df.show()
df.printSchema()
Output

Explanation:
- spark.read.csv() loads the CSV file.
- header=True treats the first row as column names.
- inferSchema=True asks Spark to infer data types from the records.
- For large datasets, providing an explicit schema can avoid the extra pass required for type inference.
7. Creating DataFrame from a Text File
Use spark.read.text() to load a plain text file. Each line becomes a row in a DataFrame containing a string column named value by default.
Example Text File:
Alice
Bob
Charlie
df = spark.read.text("employees.txt")
df.show(truncate=False)
df.printSchema()
Output

Explanation:
- spark.read.text() loads each line as a separate record.
- value is the default column name.
- truncate=False displays the complete contents of each string.
8. Creating a DataFrame from a JSON File
It store structured data as objects and arrays. Use spark.read.json() to load supported JSON data directly into a DataFrame.
{"id": 1, "name": "Alice", "age": 25}
{"id": 2, "name": "Bob", "age": 30}
{"id": 3, "name": "Charlie", "age": 28}
Code:
df = spark.read.json("employees.json")
df.show()
df.printSchema()
Output

Explanation:
- spark.read.json() loads the JSON records into a DataFrame.
- Spark infers column names and data types from the input.
- By default, the reader expects JSON Lines, where each line contains a separate JSON record.
- For a multiline JSON document, use multiLine=True when appropriate.
Displaying and Verifying a DataFrame
PySpark provides methods to inspect DataFrame contents and structure. Use them after creating a DataFrame to confirm that the data was loaded correctly.
df.show(5)
df.printSchema()
Explanation:
- show(5) displays up to five rows.
- printSchema() displays column names, data types, and nullability.
- Both methods are useful for checking the DataFrame during development.