CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 4 · Lesson 45/48

    Batch inference with pandas, pyfunc and Spark UDFs

    Use pandas to perform batch inference

    16 min read
    2% of exam
    7 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Load a registered or logged MLflow model with mlflow.pyfunc.load_model and score a pandas DataFrame on the driver
    • Build the correct models:/ URI for a Unity Catalog model version
    • Score a large Spark DataFrame in parallel with mlflow.pyfunc.spark_udf and rebuild the model's environment with env_manager
    • Choose between Series-to-Series and iterator pandas UDFs, and know when to use mapInPandas or applyInPandas instead

    Key concept

    pyfunc model as the scoring unit — An MLflow model loaded as a generic Python function exposes one predict call over pandas input. For small data you call predict on a pandas DataFrame yourself. For large data, spark_udf wraps the same model so Spark applies it to batches across the cluster.

    1.Scoring a pandas DataFrame with mlflow.pyfunc.load_model

    Batch inference means scoring a whole set of rows that already exists, such as last night's transactions or a customer table, and writing the predictions somewhere. It is not answering requests one at a time. On Databricks, every route to batch inference starts from an MLflow model loaded through the pyfunc interface. Whatever library trained the model, mlflow.pyfunc.load_model() returns an object with a predict method that takes pandas input. When you log a model, the run's Artifacts panel even generates the loading code for you, in both a pandas version and a Spark version.

    Load any Python MLflow model as a generic function and score data with itpython
    model = mlflow.pyfunc.load_model(model_path)
    model.predict(model_input)

    model_path is a model URI, the same string you use anywhere a logged or registered model is referenced. See Logged models and model URIs (runs:/, models:/). For batch scoring, what matters is that the URI alone decides which model is loaded. A run-relative path looks like runs:/{run_id}/{model-path}. A workspace-registry path names a stage, as in models:/fraud_detector/Production. load_model has no separate stage or alias argument. To get a different version, you change the URI.

    Unity Catalog models use the three-level name catalog.schema.model, followed by a slash and the version number. A model registered as retail.forecasting.demand_model is loaded at version 3 with models:/retail.forecasting.demand_model/3. The leaf name demand_model on its own does not identify it, because the model is stored inside a specific catalog and schema. Collaborators need privileges on both of those. A colon-separated name or a hand-built dbfs:/models/... path is not a registry URI either.

    Loading a specific Unity Catalog model version by numberpython
    import mlflow.pyfunc
    # Load version 1 of the model "prod.ml_team.iris_model"
    model_version_uri = "models:/prod.ml_team.iris_model/1"
    first_version = mlflow.pyfunc.load_model(model_version_uri)
    first_version.predict(test_x)

    Calling predict directly is the right choice when the data is already pandas and fits on the driver. A few thousand rows pulled into a notebook for analysis is the typical case: one load_model call and one predict call, with no cluster-wide setup. The same pattern turns into a trap when you run it the other way round. Calling toPandas() on a 50-million-row Delta table copies every record to the driver program. Spark's own guidance is to do that only on a small subset of the data. Once the data starts out as a large Spark table, scoring belongs on the cluster.

    Checkpoint 1 of 8· Fill the gap

    Which call completes this sample so that a registered or logged MLflow model can score a pandas DataFrame on the driver?

    model = mlflow.pyfunc. ? (model_path)
    model.predict(model_input)

    Checkpoint 2 of 8· Check yourself

    A nightly job needs churn scores for a 50-million-row Delta table. A colleague writes pdf = spark.table("customers").toPandas() and then model.predict(pdf) with a pyfunc model. What is the problem, and what should the job do instead?

    Checkpoint 3 of 8· Exam question

    A data scientist has a pandas DataFrame with 10,000 rows already loaded in the driver's memory and a model registered at models:/churn_model/Production. They want to generate predictions for this one-off analysis with the least setup overhead. Which approach best fits this situation?

    Checkpoint 4 of 8· Exam question

    A team registered an MLflow model in Unity Catalog under the three-level name retail.forecasting.demand_model and wants to load version 3 of that model to run pandas-based batch predictions in a notebook. Which model loading call is correct?

    Sources123

    2.Distributing the model with mlflow.pyfunc.spark_udf

    mlflow.pyfunc.spark_udf turns the same pyfunc model into a Spark UDF. Spark then applies it to the rows of a Spark DataFrame across the cluster, and the work never passes through a single pandas DataFrame on the driver. You give it the active spark session and a model URI, then use the returned UDF like any other column expression. Usually that means withColumn("prediction", ...), followed by writing the result to a new Delta table. MLflow positions this route for scoring on a Spark cluster, whether as a batch job or as a Spark Streaming job.

    Export a model as a Spark UDF and add a prediction column to a tablepython
    # load input data table as a Spark DataFrame
    input_data = spark.table(input_table_name)
    model_udf = mlflow.pyfunc.spark_udf(spark, model_path)
    df = input_data.withColumn("prediction", model_udf())

    Batch scoring like this suits work where throughput and cost matter more than per-request latency, with results arriving in minutes. Looping over 50 million rows in a notebook and calling a real-time endpoint once per row inverts that trade-off. It routes a throughput job through infrastructure built for individual requests, and the driver loop does all the waiting.

    The UDF runs the model on cluster workers, and those workers need the library versions the model was trained with. The model's logged requirements record those versions; see Model signature, input example and pip requirements. Pass env_manager="virtualenv" to spark_udf, and MLflow restores those dependencies inside the UDF's own context while leaving the notebook's environment untouched. That is the fix when a cluster's installed scikit-learn differs from the one in training and predictions drift or fail to load. MLflow warns you about such a mismatch when you load the model, but it does not correct it. On the driver, mlflow.pyfunc.get_model_dependencies returns a requirements file that you can install with %pip install.

    Choosing a batch scoring call for where the data lives
    SituationCallWhy
    Small pandas DataFrame already on the drivermlflow.pyfunc.load_model(uri).predict(pdf)No cluster setup; predict accepts pandas input
    Large Spark table to score and write backmlflow.pyfunc.spark_udf(spark, uri) with withColumnSpark applies the model across the cluster
    Workers' libraries differ from trainingspark_udf(..., env_manager="virtualenv")Restores the model's dependencies inside the UDF only
    Large table pulled with toPandas() then predictAvoidCollects every record to the driver

    Checkpoint 5 of 8· Check yourself

    After a cluster upgrade, a spark_udf scoring job starts producing drifting predictions. The workers now run a different scikit-learn version from the one the model was trained with. What fixes this without changing the notebook's own environment?

    Checkpoint 6 of 8· Exam question

    A data engineer has a Delta table with 50 million transaction rows and a model registered at models:/fraud_detector/Production. They need to score every row and write predictions to a new Delta table while distributing the scoring work across the cluster. Which approach should they use?

    Sources14

    3.Writing your own pandas UDF for model scoring

    Sometimes you need custom pre- or post-processing around the model, or a model object that spark_udf does not wrap for you. In that case you write the pandas UDF yourself, and spark_udf is in fact the packaged version of this same mechanism. Databricks recommends pandas UDFs for scaling batch and streaming inference across a cluster. A pandas UDF uses Apache Arrow to move data between the JVM and Python and works on whole pandas objects instead of single rows. That vectorization is why it can run up to 100x faster than a row-at-a-time Python UDF.

    The basic form is Series to Series. You declare it with the pandas_udf decorator and the type hints pd.Series -> pd.Series, and you use it in select or withColumn. Spark splits the data into batches of rows, calls your function once per batch, and concatenates the results. Each output Series must be the same length as its input. The Series your function receives is one internal batch, not the whole column, so anything computed across 'the column' inside the function is really computed per batch.

    The answer is once per batch, which is wasted work for any model that is expensive to deserialize. The iterator form fixes this. The function takes Iterator[pd.Series] and returns Iterator[pd.Series], which lets it do setup once and then loop over the incoming batches, yielding one result per batch. This variant exists for exactly the case of loading a model file and applying it to every input batch. The total output length across all yielded batches must still match the total input length. Wrap the loop in try/finally, or use a context manager, so that any resources are released at the end.

    Iterator UDF: state is set up before the batch loop, then reused for every batchpython
    # In the UDF, you can initialize some state before processing batches.
    # Wrap your code with try/finally or use context managers to ensure
    # the release of resources at the end.
    y = 1  # value captured by the UDF closure
    
    @pandas_udf("long")
    def plus_y(batch_iter: Iterator[pd.Series]) -> Iterator[pd.Series]:
        try:
            for x in batch_iter:
                yield x + y
        finally:
            pass  # release resources here, if any

    A basic iterator UDF takes a single Spark column. Most models need several features, so there is a multi-column variant with the hint Iterator[Tuple[pd.Series, ...]] -> Iterator[pd.Series]. Each item from the iterator is a tuple holding one Series per input column, and the UDF is called with that many columns. It follows the same rules as the single-column iterator, including setting up state before the loop.

    pandas UDF type hints and when each fits model scoring
    Type hintInput columnsFits when
    pd.Series -> pd.SeriesOne or moreCheap per-batch logic with no setup cost
    Iterator[pd.Series] -> Iterator[pd.Series]OneAn expensive setup step, such as loading a model, should happen before the batches
    Iterator[Tuple[pd.Series, ...]] -> Iterator[pd.Series]SeveralThe same as above, for a model with several feature columns

    Checkpoint 7 of 8· Match them up

    You are writing your own pandas UDF to score a model on a Spark table. Match each type hint to how it behaves.

    Tap a term, then the definition that fits it.

    Sources456

    4.DataFrame-level scoring with mapInPandas and applyInPandas

    pandas function APIs hand your function whole pandas DataFrames instead of individual columns. They run on the same Arrow machinery as pandas UDFs, and type hints are optional. Two of them matter for inference.

    mapInPandas takes an iterator of pandas DataFrames and yields an iterator of pandas DataFrames, and you declare the output schema yourself. Because the function receives an iterator, you can load the model once before the loop, just as in an iterator UDF. A pandas UDF has to emit exactly one value per input row. mapInPandas can return output of any length, so one function can score, filter out low-confidence rows and add several output columns.

    mapInPandas: the function receives and yields pandas DataFrames, here returning fewer rows than it gotpython
    df = spark.createDataFrame([(1, 21), (2, 30)], ("id", "age"))
    
    def filter_func(iterator):
        for pdf in iterator:
            yield pdf[pdf.id == 1]
    
    df.mapInPandas(filter_func, schema=df.schema).show()

    groupBy().applyInPandas() follows a split-apply-combine pattern. Each group arrives as a single pandas DataFrame containing all of its rows, and the results are combined back into a Spark DataFrame using a schema you supply. It fits per-group scoring, such as a separate forecasting model for each store. The cost is memory. A whole group is loaded before your function runs, and maxRecordsPerBatch does not split groups. One oversized store can therefore cause an out-of-memory error even when every other group is small. Use mapInPandas when rows can be scored independently, and keep applyInPandas for logic that really needs all of a group at once.

    Checkpoint 8 of 8· Fill the gap

    This function gets an iterator of pandas DataFrames and yields fewer rows than it receives. Which DataFrame method runs it across the cluster without grouping the data first?

    df = spark.createDataFrame([(1, 21), (2, 30)], ("id", "age"))
    
    def filter_func(iterator):
        for pdf in iterator:
            yield pdf[pdf.id == 1]
    
    df. ? (filter_func, schema=df.schema).show()

    Sources7

    Sources

    (7)

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

    1. 1.
      “For Python MLflow models, an additional option is to use mlflow.pyfunc.load_model() to load the model as a generic Python function.”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “A panel opens to the right showing code you can use to load the logged model and make predictions on Spark or pandas DataFrames.”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “a registered model path (such as models:/{model_name}/{model_stage}).”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “export the model as an Apache Spark UDF to use for scoring on a Spark cluster, either as a batch job”
      ↩︎ Distributing the model with mlflow.pyfunc.spark_udf
      “This restores model dependencies in the context of the PySpark UDF and does not affect the outside environment.”
      ↩︎ Distributing the model with mlflow.pyfunc.spark_udf
      “MLflow warns you if a mismatch is detected between the current environment and the model's dependencies.”
      ↩︎ Distributing the model with mlflow.pyfunc.spark_udf
      “you can call mlflow.pyfunc.get_model_dependencies to retrieve and download the model dependencies.”
      ↩︎ Distributing the model with mlflow.pyfunc.spark_udf
      “For Python MLflow models, an additional option is to use mlflow.pyfunc.load_model() to load the model as a generic Python function.”
      ↩︎ Key concept
      “When you load a model as a PySpark UDF, specify env_manager="virtualenv" in the mlflow.pyfunc.spark_udf call.”
      ↩︎ Exam trap 4
      “make predictions on Spark or pandas DataFrames”
      ↩︎ Prediction
      “When you load a model as a PySpark UDF, specify env_manager="virtualenv" in the mlflow.pyfunc.spark_udf call.”
      ↩︎ Checkpoint
    2. 2.
      “You can also load model versions by version number:”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “Collaborators must also have the USE CATALOG and USE SCHEMA privileges on the catalog and schema containing the model.”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “model_version_uri = "models:/prod.ml_team.iris_model/1"”
      ↩︎ Exam trap 1
    3. 3.
      “collection of all records in the DataFrame to the driver program”
      ↩︎ Scoring a pandas DataFrame with mlflow.pyfunc.load_model
      “collection of all records in the DataFrame to the driver program”
      ↩︎ Exam trap 2
      “Even with Arrow, toPandas() results in the collection of all records in the DataFrame to the driver program”
      ↩︎ Checkpoint
    4. 4.
      “Batch and streaming scoring supports high-throughput, low-cost scoring at latencies as low as minutes.”
      ↩︎ Distributing the model with mlflow.pyfunc.spark_udf
      “Use Spark Pandas UDFs to scale batch and streaming inference across a cluster.”
      ↩︎ Writing your own pandas UDF for model scoring
    5. 5.
      “pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
      ↩︎ Writing your own pandas UDF for model scoring
      “Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
      ↩︎ Writing your own pandas UDF for model scoring
      “loading a machine learning model file to apply inference to every input batch”
      ↩︎ Writing your own pandas UDF for model scoring
      “The length of the entire output in the iterator should be the same as the length of the entire input.”
      ↩︎ Writing your own pandas UDF for model scoring
      “The wrapped pandas UDF takes multiple Spark columns as an input.”
      ↩︎ Writing your own pandas UDF for model scoring
      “loading a machine learning model file to apply inference to every input batch”
      ↩︎ Exam trap 3
      “useful when the UDF execution requires initializing some state, for example, loading a machine learning model file to apply inference to every input batch”
      ↩︎ Checkpoint
    6. 7.
      “It can return output of arbitrary length in contrast to some pandas UDFs such as Series to Series.”
      ↩︎ DataFrame-level scoring with mapInPandas and applyInPandas
      “All data for a group is loaded into memory before the function is applied.”
      ↩︎ DataFrame-level scoring with mapInPandas and applyInPandas
      “This can lead to out of memory exceptions, especially if the group sizes are skewed.”
      ↩︎ DataFrame-level scoring with mapInPandas and applyInPandas

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

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