CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 18/32

    Sorting, schema inspection and collecting DataFrame rows in PySpark

    Perform operations on DataFrames such as sorting, iterating, printing schema, and conversion between DataFrame and sequence/list formats.

    18 min read
    3% of exam
    16 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Ways to express sort direction with sort/orderBy
    FormExampleEffect
    Column expressiondf.sort(df.age.desc())age descending
    Function expressiondf.sort(sf.asc("age"))age ascending
    Name plus keyworddf.sort("age", ascending=False)age descending
    Mixed names and expressionsdf.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.

    Two keys: age descending, then name ascending among the tied agespython
    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|
    # +---+-----+

    Checkpoint 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?

    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?

    Sources12345

    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.

    Four ways to inspect the same schema
    MemberKindWhat you get
    printSchema(level)methodA printed tree; level limits how deep nested structs are expanded
    schemapropertyA StructType of StructField entries (name, type, nullable)
    dtypespropertyA list of (column name, type string) tuples, e.g. ('age', 'bigint')
    columnspropertyA list of column-name strings
    printSchema with a level: level 1 stops at the struct, level 2 opens itpython
    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?

    Sources678

    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.

    Row-returning methods and what they give back
    MethodReturns
    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.

    Attribute access and key access return the same plain valuespython
    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.

    From collected Rows to a list of values, or to a list of dictspython
    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'}]

    Checkpoint 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?

    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?

    Sources91011

    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.

    Sources12137

    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.

    A list of tuples with column names becomes a DataFramepython
    # 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?

    Sources1415167

    Sources

    (16)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    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
    2. 3.
      “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
    3. 4.
      “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
    4. 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
    5. 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
    6. 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
    7. 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
    8. 14.
      “When a list of column names is provided, the type of each column is inferred from data.”
      ↩︎ Converting between Python lists, pandas and DataFrames
    9. 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

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.