Menu
CoddyTech

Your First DataFrame

Part of the Fundamentals section of Coddy's PySpark journey. Lesson 2 of 18.

Create a DataFrame with spark.createDataFrame(rows, schema). Each tuple is one row. The schema lists column names and types in the same order as the tuple values. Here, string holds text and int holds whole numbers.

people = spark.createDataFrame(
    [("Mira", 8), ("Sol", 11)],
    "name string, points int"
)
print(people.count())

This example prints 2. The schema describes the columns; it does not add a row. count() returns the number of data rows.

An empty list has no records from which Spark could discover column types. You can still create an empty table by supplying the schema explicitly:

empty = spark.createDataFrame([], "name string, points int")
print(empty.count())

This prints 0. The table has the declared columns but no rows.

challenge icon

Challenge

Beginner

Create a DataFrame named items with rows ("pen", 4), ("book", 2), and ("bag", 1). Use schema item string, quantity int. Print its row count.

Try it yourself

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Learning").getOrCreate()
# Create items here.
print(0)
spark.stop()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Python compiler