What you will be able to do
- Order a DataFrame on several columns with mixed directions and explicit null placement using sort or orderBy
- Read a DataFrame's structure as a printed tree with printSchema, or as Python data through schema, dtypes and columns
- Pull rows to the driver with collect, take, head, tail or first, and read Row fields by attribute, by key or as a dict
- Choose between collect and toLocalIterator for iterating rows, based on how much driver memory each uses
- Build a DataFrame from a Python list and convert one to pandas with toPandas, knowing what Arrow does and does not change
Key concept
Driver-side materialisation — A DataFrame is spread across the cluster until you call a method that returns plain Python objects, such as collect, take, toLocalIterator or toPandas. At that point the rows are copied into the driver process, so the size of the result has to fit in driver memory.
1.Ordering rows with sort and orderBy
sort and orderBy are the same method under two names. Both return a new DataFrame ordered by the columns you pass, and both sort ascending unless told otherwise. Neither one is a partition-local version of the other. Some people expect sort to behave like SQL's SORT BY, which only orders rows inside each partition. It doesn't: on a DataFrame, orderBy is just an alias for sort.
Direction can be set in two ways. The first is to build a sort expression per column: col("x").asc(), col("x").desc(), or the function forms asc("x") and desc("x") from pyspark.sql.functions. The second is to pass plain column names along with the ascending keyword. That keyword takes either one boolean for every column or a list of booleans. A list must have exactly as many entries as there are columns. Columns can also be given by position. Positions start at 1, not at 0, and a negative position sorts that column descending.
| Form | Example | Effect |
|---|---|---|
| Column expression | df.sort(df.age.desc()) | age descending |
| Function expression | df.sort(sf.asc("age")) | age ascending |
| Name plus keyword | df.sort("age", ascending=False) | age descending |
| Mixed names and expressions | df.orderBy(sf.desc("age"), "name") | age descending, then name ascending |
With several sort keys, they apply from left to right. Every row is ordered by the first expression. The second expression only decides the order among rows that tie on the first, and so on down the list. That means the order of the arguments is the order of priority. For "department A to Z, highest salary first within each department", write col("department").asc(), col("salary").desc(), in that order. If you swap the two, the whole result is ordered by salary. If you pass bare names ("department", "salary"), both columns sort ascending. A string such as "-salary" is read as a column name, not as a descending flag. Only an integer position can be made negative.
df = spark.createDataFrame([
(2, "Alice"), (2, "Bob"), (5, "Bob")], schema=["age", "name"])
df.orderBy(sf.desc("age"), "name").show()
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2|Alice|
# | 2| Bob|
# +---+-----+Use the null-aware sort expressions when you need to control where nulls go: asc_nulls_first, asc_nulls_last, desc_nulls_first and desc_nulls_last. Each exists both as a Column method and as a function. In Spark SQL's ORDER BY, if no null order is given, NULLs come first in an ascending sort and last in a descending one. Writing df.age.asc_nulls_last() states the placement in the code, so nobody has to remember that default. For example, a ranking report that should list unscored entries at the bottom needs asc_nulls_last. A plain asc would put them at the top.
A sort is not a lasting property of the data. Sorting is costly at scale. If you save sorted output and read it back with Spark, the rows are not guaranteed to come back in that order. Sort as close as possible to the step that needs the order, such as limit(10) for a top-ten list or a final display, rather than early in a pipeline in the hope that the order survives.
Checkpoint 1 of 9· Fill the gap
The output below lists age 5 first, then the two age-2 rows in name order. Which function completes the sort expression?
df = spark.createDataFrame([
(2, "Alice"), (2, "Bob"), (5, "Bob")], schema=["age", "name"])
df.orderBy(sf. ? ("age"), "name").show()
# +---+-----+
# |age| name|
# +---+-----+
# | 5| Bob|
# | 2|Alice|
# | 2| Bob|
# +---+-----+Age 5 comes before age 2, so the first key sorts descending, and of the options shown only sf.desc gives exactly this code. The bare name "name" sorts ascending and only breaks ties among the age-2 rows, which is why Alice comes before Bob.
Source: docs.databricks.comCheckpoint 2 of 9· Check yourself
A pipeline needs one total order across the whole DataFrame. A colleague changes df.sort("ts") to df.orderBy("ts") "to get a global sort". What does this change do?
On a DataFrame, orderBy is just another name for sort. Neither one is a partition-local version of the other, so both calls return the same sorted result.
“orderBy is an alias for sort.”Source: docs.databricks.com
Checkpoint 3 of 9· Exam question
A report needs rows ordered by department ascending, and within each department by salary descending. Given:
from pyspark.sql.functions import col
df.orderBy(___).show()
Which argument produces the required ordering?
Correct answer: A — col("department").asc(), col("salary").desc()
- A. Passing
col("department").asc()followed bycol("salary").desc()sorts primarily on department in ascending order and breaks ties within each department by descending salary, matching the requirement exactly. - B. Plain string column names default to ascending order for both columns, so salary within each department would sort lowest-to-highest instead of the required descending order.
- C. This reverses the department direction to descending, which sorts departments Z-to-A instead of A-to-Z, and also sorts salary ascending, so neither direction matches the requirement.
- D.
orderBydoes not interpret a leading-on a string as a descending marker; this list form only accepts plain column-name strings and always sorts them ascending, so salary would not be descending. - E. This sorts primarily by salary descending and only uses department as the tiebreaker, which reorders the whole result by salary first instead of grouping rows by department as the primary key.
2.Reading a DataFrame's schema: printSchema, schema, dtypes and columns
Spark offers four ways to look at a DataFrame's structure. One is for people to read and three return values your code can use. printSchema() prints the schema to the console as a tree, showing each column's type and nullability. It returns nothing. The other three are properties that hand back Python objects you can test or loop over.
| Member | Kind | What you get |
|---|---|---|
| printSchema(level) | method | A printed tree; level limits how deep nested structs are expanded |
| schema | property | A StructType of StructField entries (name, type, nullable) |
| dtypes | property | A list of (column name, type string) tuples, e.g. ('age', 'bigint') |
| columns | property | A list of column-name strings |
df = spark.createDataFrame([(1, (2, 2))], ["a", "b"])
df.printSchema(1)
# root
# |-- a: long (nullable = true)
# |-- b: struct (nullable = true)
df.printSchema(2)
# root
# |-- a: long (nullable = true)
# |-- b: struct (nullable = true)
# | |-- _1: long (nullable = true)
# | |-- _2: long (nullable = true)The optional level argument is useful on wide, deeply nested data such as JSON. On that kind of data a full tree can run to hundreds of lines. printSchema(1) lists just the top-level columns and labels nested ones as struct. Leave the argument out to print every level.
Use the properties when the answer feeds into code. "email" in df.columns is a quick way to check that a column exists. df.dtypes gives the types as short strings, which is handy for picking out every string column. Note that dtypes calls a Python int column bigint, while printSchema shows the same column as long. df.schema returns the full StructType. That includes nullability, which neither of the list properties carries.
Checkpoint 4 of 9· Check yourself
Before writing to a table, a job must fail if any column of df is nullable. The check runs in code, not by eye. Which member should it read?
df.schema returns a StructType whose StructField entries hold the name, type and nullable flag, so code can test the flag directly. printSchema shows nullability but only prints it and returns nothing. dtypes and columns don't include nullability at all.
“Returns the schema of this DataFrame as a StructType.”Source: docs.databricks.com
3.Bringing rows to the driver as Row objects
Several methods turn a distributed DataFrame into a Python list of Row objects on the driver. They differ in how many rows they bring back. collect() returns every row. Only use it when you know the result is small, because the whole result is loaded into driver memory. The others return a fixed number of rows, so they are safe on a DataFrame of any size.
| Method | Returns |
|---|---|
| collect() | All records as a list of Row |
| take(num) | The first num rows as a list of Row |
| head(n) | The first n rows |
| tail(num) | The last num rows as a list of Row |
| first() | The first row as a single Row |
A Row holds the values themselves, not column objects. You can read a field as an attribute (row.name) or by key (row["name"]), and both return the plain value. So for a first row holding Alice and 30, rows[0].name gives Alice and rows[0]["age"] gives 30. You get neither a nested Row nor the column name. key in row checks whether a field name exists.
from pyspark.sql import Row
row = Row(name="Alice", age=11)
row
# Row(name='Alice', age=11)
row['name'], row['age']
# ('Alice', 11)
row.name, row.age
# ('Alice', 11)When the next step expects plain dictionaries, such as a JSON serializer, an HTTP payload or a test fixture, call asDict() on each Row. It returns a dict that maps column names to values. A list comprehension over the result of collect() gives you one dict per row. Calls like toPandas() and select() will not work here because they belong to the DataFrame, not to a Row, and a Row has no schema or rdd property either.
rows = df.collect()
[row["name"] for row in rows]
# ['Tom', 'Alice', 'Bob']
[row.asDict() for row in rows]
# [{'age': 14, 'name': 'Tom'}, {'age': 23, 'name': 'Alice'}, {'age': 16, 'name': 'Bob'}]asDict has two details worth knowing. First, nested structs stay as Row objects unless you call asDict(True), which turns nested Rows into dicts as well. Second, a Row produced by a join can contain two fields with the same name. In that case asDict keeps only one of them, so rename overlapping columns before you collect.
Checkpoint 5 of 9· Fill the gap
A JSON serializer downstream needs one plain Python dict per collected row, mapping column names to values. Which Row method fills the blank?
rows = df.collect()
[row["name"] for row in rows]
# ['Tom', 'Alice', 'Bob']
[row. ? () for row in rows]
# [{'age': 14, 'name': 'Tom'}, {'age': 23, 'name': 'Alice'}, {'age': 16, 'name': 'Bob'}]asDict() is the Row method that returns a dict mapping column names to values, so the list comprehension gives one dict per row. toJSON, toPandas and collect are DataFrame methods, not Row methods, so they won't work on a single collected Row.
Source: docs.databricks.comCheckpoint 6 of 9· Exam question
A df has columns name and age, and its first row holds Alice and 30. Given:
rows = df.select("name", "age").collect()
print(rows[0].name, rows[0]["age"])
What does this print?
Correct answer: A — Alice 30
- A.
collect()returns a Python list ofRowobjects, andRowsupports both attribute access (rows[0].name) and dictionary-style indexing (rows[0]["age"]), so this prints the two underlying values, Alice and 30. - B. Dot notation on a
Rowreturns the individual field value, not the wholeRowobject, sorows[0].nameevaluates to the stringAlicerather than a repr of the entire row. - C.
Rowis a subclass oftuplethat specifically adds named attribute access, sorows[0].nameis valid syntax and does not raise an error. - D. Indexing a
Rowwith a column name string returns that single field's value, not anotherRowwrapping the remaining fields, sorows[0]["age"]evaluates to the integer 30. - E.
collect()materializes data rows, not a header of column names, so this prints the row's actual values rather than the schema's field names.
Checkpoint 7 of 9· Exam question
A pipeline needs to hand a downstream JSON serializer a Python list of dictionaries, one per row, mapping each column name to its value. Given:
data = df.collect()
records = [___ for row in data]
Which expression completes the list comprehension?
Correct answer: A — row.asDict()
- A.
Row.asDict()converts a singleRowinto a Python dictionary keyed by column name, so mapping it acrossdatayields exactly the list of per-row dictionaries the serializer needs. - B.
toPandas()is aDataFramemethod that builds a pandas DataFrame from the whole dataset; an individualRowobject has notoPandasmethod and calling it raises anAttributeError. - C. A
Rowobject has noschemaattribute; schema information lives on the parentDataFrame, so this raises anAttributeErrorrather than producing a dictionary of values. - D.
selectis aDataFrametransformation that returns a newDataFrame; aRowobject has noselectmethod, so this call fails with anAttributeError. - E.
rddandcollectare attributes of aDataFrame, not of an individualRow, so calling them on a single row raises anAttributeErrorinstead of returning a dictionary.
4.Iterating rows: toLocalIterator versus collect and foreach
To loop over every row in driver-side Python code, you can use collect() and a for-loop, or use toLocalIterator(). They produce the same rows. The difference is how much of the data has to sit in driver memory at once.
toLocalIterator() fetches one partition at a time and hands you its rows. Peak driver memory is set by the largest partition, not by the full DataFrame. Passing prefetchPartitions=True tells Spark to fetch the next partition before you need it. The loop waits less, but memory can rise to the size of the two largest partitions. If data skew leaves one huge partition, the driver still has to hold that whole partition.
foreach(f) iterates differently. It applies a function to every Row of the DataFrame and returns nothing to the caller. Use it for per-row side effects. Use toLocalIterator when the rows need to end up in driver-side Python. For a quick look rather than a loop, show(n) prints the first n rows to the console as a table.
Checkpoint 8 of 9· Match them up
A driver-side job handles rows from a large DataFrame in different ways. Match each call to the job it suits.
Tap a term, then the definition that fits it.
toLocalIterator and collect produce the same rows, but toLocalIterator fetches one partition at a time, while collect puts the whole result in driver memory. foreach applies a function to each Row and returns nothing, and show(n) only prints a preview.
“Returns an iterator that contains all of the rows in this DataFrame.”Source: docs.databricks.com
5.Converting between Python lists, pandas and DataFrames
Data can move in both directions. spark.createDataFrame builds a DataFrame from a Python list, as well as from an RDD, a pandas DataFrame, a NumPy array or a PyArrow table. A list of tuples needs column names to be useful. Without them, Spark names the columns _1, _2 and so on. When you supply only names, Spark infers each column's type from the data. A list of dicts or Row objects already carries field names.
# Create a DataFrame with column names specified.
spark.createDataFrame([('Alice', 1)], ['name', 'age']).show()
# +-----+---+
# | name|age|
# +-----+---+
# |Alice| 1|
# +-----+---+toPandas() goes the other way. It returns a pandas.DataFrame, works only if pandas is installed, and loads every row into driver memory, just like collect(). Setting spark.sql.execution.arrow.pyspark.enabled to true makes Spark use Apache Arrow for the transfer. Arrow is a columnar format for moving data between the JVM and Python processes efficiently, and it also speeds up createDataFrame(pandas_df). The results are the same either way. If an error occurs before the computation starts, Spark can fall back to the non-Arrow path. Arrow makes the copy faster, but it does not make a large copy safe. Even with Arrow, every record still ends up on the driver.
If you need pandas-style code on data too big for the driver, use the Pandas API on Spark (pyspark.pandas). df.pandas_api() converts a DataFrame into a pandas-on-Spark DataFrame. That object stays a distributed Spark frame, while toPandas() collects all the data to the driver. Choose toPandas() for a small, already-aggregated result headed for a plotting or modelling library. Choose pandas_api() when the full dataset must stay on the cluster.
Checkpoint 9 of 9· Check yourself
With spark.sql.execution.arrow.pyspark.enabled set to true, an engineer calls toPandas() on a 200 GB DataFrame so they can keep writing pandas-style code. What should they expect?
Arrow only speeds up the copy between the JVM and Python and gives the same results. toPandas() still collects every record to the driver. pandas_api() is the option that keeps the data as a distributed frame on the cluster.
“Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”Source: docs.databricks.com
Sources
(16)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“orderBy is an alias for sort.”
↩︎ Ordering rows with sort and orderBy“orderBy is an alias for sort.”
↩︎ Exam trap 1 - 2.
“If a list is specified, the length of the list must equal the length of the cols.”
↩︎ Ordering rows with sort and orderBy“A column ordinal starts from 1, which is different from the 0-based __getitem__. If a column ordinal is negative, it means sort descending.”
↩︎ Ordering rows with sort and orderBy - 3.https://docs.databricks.com/aws/en/pyspark/basicsOfficial docs
“By default these methods sort in ascending order”
↩︎ Ordering rows with sort and orderBy“if you store sorted data and reload the data with Spark, order is not guaranteed”
↩︎ Ordering rows with sort and orderBy“if you store sorted data and reload the data with Spark, order is not guaranteed”
↩︎ Exam trap 2 - 4.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-orderbyOfficial docs
“If there are duplicate values for the first expression the second expression is used to resolve order within the group of duplicates”
↩︎ Ordering rows with sort and orderBy“If null_sort_order is not specified, then NULLs sort first if sort order is ASC and NULLS sort last if sort order is DESC.”
↩︎ Ordering rows with sort and orderBy“The resulting order not deterministic if there are duplicate values across all order by expressions.”
↩︎ Ordering rows with sort and orderBy - 5.
“null values return before non-null values”
↩︎ Ordering rows with sort and orderBy - 6.
“Optionally allows to specify how many levels to print if schema is nested.”
↩︎ Reading a DataFrame's schema: printSchema, schema, dtypes and columns - 7.
“Returns the schema of this DataFrame as a StructType.”
↩︎ Reading a DataFrame's schema: printSchema, schema, dtypes and columns“Retrieves the names of all columns in the DataFrame as a list.”
↩︎ Reading a DataFrame's schema: printSchema, schema, dtypes and columns“Prints the first n rows of the DataFrame to the console.”
↩︎ Iterating rows: toLocalIterator versus collect and foreach“Converts the existing DataFrame into a pandas-on-Spark DataFrame.”
↩︎ Converting between Python lists, pandas and DataFrames“Returns an iterator that contains all of the rows in this DataFrame.”
↩︎ Checkpoint - 8.
“# [('age', 'bigint'), ('name', 'string')]”
↩︎ Reading a DataFrame's schema: printSchema, schema, dtypes and columns - 9.
“all the data is loaded into the driver's memory”
↩︎ Bringing rows to the driver as Row objects“all the data is loaded into the driver's memory”
↩︎ Key concept - 10.
“like dictionary values (row[key])”
↩︎ Bringing rows to the driver as Row objects“like attributes (row.key)”
↩︎ Exam trap 5 - 11.
“Turns the nested Rows to dict (default: False).”
↩︎ Bringing rows to the driver as Row objects“one of the duplicate fields will be selected by asDict”
↩︎ Bringing rows to the driver as Row objects - 12.
“The iterator will consume as much memory as the largest partition in this DataFrame.”
↩︎ Iterating rows: toLocalIterator versus collect and foreach“If Spark should pre-fetch the next partition before it is needed.”
↩︎ Iterating rows: toLocalIterator versus collect and foreach“With prefetch it may consume up to the memory of the 2 largest partitions.”
↩︎ Exam trap 3 - 13.
“Applies the f function to all Row of this DataFrame.”
↩︎ Iterating rows: toLocalIterator versus collect and foreach - 14.https://docs.databricks.com/aws/en/pyspark/reference/classes/sparksession/createDataFrameOfficial docs
“When a list of column names is provided, the type of each column is inferred from data.”
↩︎ Converting between Python lists, pandas and DataFrames - 15.
“This is only available if Pandas is installed and available.”
↩︎ Converting between Python lists, pandas and DataFrames - 16.
“To use Arrow for these methods, set the Spark configuration spark.sql.execution.arrow.pyspark.enabled to true.”
↩︎ Converting between Python lists, pandas and DataFrames“Using the Arrow optimizations produces the same results as when Arrow is not enabled.”
↩︎ Converting between Python lists, pandas and DataFrames“Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”
↩︎ Exam trap 4“Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”
↩︎ Checkpoint