Read CSV Files
Part of the Fundamentals section of Coddy's PySpark journey. Lesson 15 of 18.
Read a CSV file with spark.read. CSV is text, so provide a schema to control column types. Set header to True when the first record contains column names; otherwise those names are treated as data.
df = (spark.read.option("header", True)
.schema("city string, visitors int")
.csv(path))The path names a file in the current workspace. An explicit schema handles an empty file with a header and keeps integer columns numeric. Spark can infer a schema, but that requires inspecting the data and may produce types that differ across files.
A quoted CSV field can contain commas. For example, "large, blue",0 contains two fields: the text large, blue and the number 0. The CSV reader handles the quotes; splitting each line at every comma would break this record.
Challenge
EasyComplete load_data(spark, path). Read the CSV at the supplied path, which has a header item,stock. Return both columns, with stock as an integer. Keep all rows.
The checker supplies the path; use the path argument. Schema: item string, stock int. The session and F are available. Do not print; the checker reads and displays the result rows.
Try it yourself
def load_data(spark, path):
return spark.createDataFrame([], 'item string, stock int')
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