CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 22/48

    Comparing two features: Pearson correlation and contingency tables in Spark

    Compare two categorical or two continuous features using the appropriate method

    17 min read
    2.11% of exam
    9 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Choose Pearson correlation for a pair of continuous features and a contingency table for a pair of categorical features
    • Compute Pearson correlation with df.stat.corr, DataFrame.corr or the SQL corr aggregate
    • Explain why covariance cannot replace correlation when comparing feature pairs
    • Build a contingency table with df.stat.crosstab and read its layout as the input to a chi-square test
    • Reject comparison methods that do not fit the feature types involved

    Key concept

    The comparison method follows the feature pair's type — Two continuous (numeric) features are compared with Pearson correlation, a single number describing how closely they move together along a straight line. Two categorical features have no numeric values to correlate, so you compare them by counting how often each pair of categories occurs together in a contingency table.

    1.Choosing a comparison by feature type

    Before a feature goes into a model, you usually want to know how it relates to the other columns. Does sale_price rise with square_footage? Does preferred_channel depend on customer_segment? Spark can answer both questions, but it uses a different tool for each. The deciding factor is what kind of values the two columns hold.

    Two continuous columns get a correlation. Spark's corr takes two numeric columns and returns one double: the Pearson correlation coefficient. Two categorical columns get a contingency table. Spark's crosstab takes two columns and returns a whole DataFrame of counts, with one cell for each combination of values. The first method sums up a relationship in a single number. The second lists every combination and how often it occurs, so you can see, or test, whether the categories depend on each other.

    Both methods belong to DataFrameStatFunctions, the object that df.stat returns. Next to them sits cov, which looks like a third option for numeric pairs but is less useful for comparing them. For charts of the same pairs, such as scatter plots or stacked bars, see visualizing categorical and continuous features. The methods here compute the numbers and tables behind those charts.

    The three pairwise methods on df.stat
    MethodSuited toReturnsWhat it tells you
    corr(col1, col2, method)Two continuous columnsA doubleStrength and direction of the linear relationship (Pearson only)
    cov(col1, col2)Two continuous columnsA doubleSample covariance, in the units of the two columns
    crosstab(col1, col2)Two categorical columnsA DataFramePair-wise frequency counts of every value combination

    Checkpoint 1 of 9· Match them up

    Match each df.stat method to the result it gives you

    Tap a term, then the definition that fits it.

    Sources1

    2.Pearson correlation with df.stat.corr

    df.stat.corr("col1", "col2") computes the Pearson correlation coefficient of two columns directly on a Spark DataFrame, with no conversion to pandas. df.corr is the same method under another name, so df.corr("engine_size", "fuel_consumption") and df.stat.corr("engine_size", "fuel_consumption") return the same float.

    The optional method argument looks like a way to pick a type of correlation, but "pearson" is the only value it accepts. Either leave it out or pass "pearson". There is no rank-based alternative behind it.

    Pearson correlation on two pairs of numeric columnspython
    df = spark.createDataFrame([(1, 12), (10, 1), (19, 8)], ["c1", "c2"])
    df.stat.corr("c1", "c2")
    # -0.3592106040535498
    
    df = spark.createDataFrame([(11, 12), (10, 11), (9, 10)], ["small", "bigger"])
    df.stat.corr("small", "bigger")
    # 1.0

    The coefficient runs from -1 to 1. Its sign gives the direction and its size gives the strength. In the second DataFrame, bigger is always small plus one, so the points lie on a straight rising line and the result is exactly 1.0. The c1/c2 pair comes out at about -0.36: as c1 grows, c2 tends to fall, but the points are far from a line. Run the same call on square_footage and sale_price across thousands of home sales and you get one value in that range. It tells you how strongly the two columns move together along a straight line, and in which direction.

    Checkpoint 2 of 9· Check yourself

    A teammate wants a rank-based correlation between two numeric columns and plans to call df.stat.corr("tenure", "spend", method="spearman"). What should you tell them?

    Sources23

    3.Covariance is a different, scale-dependent number

    df.stat.cov sits right next to corr and takes the same two numeric columns, so it is easy to use by mistake. It returns the sample covariance. The sign still gives the direction, but the size is measured in the units of the two columns multiplied together.

    Sample covariance of the same c1/c2 pair whose correlation is -0.359python
    df = spark.createDataFrame([(1, 12), (10, 1), (19, 8)], ["c1", "c2"])
    df.cov("c1", "c2")
    # -18.0

    The same data gives two very different numbers. Correlation reports the c1/c2 relationship as weak, at -0.36. Covariance reports -18.0. That -18.0 says nothing about whether the relationship is weak or strong, because it would change if c1 were recorded in different units. Switch square_footage from square feet to square metres and its covariance with sale_price shrinks, while the correlation stays the same. That is why you can compare correlations across feature pairs but not covariances.

    Checkpoint 3 of 9· Fill the gap

    Running this call on the c1/c2 pair (Pearson coefficient about -0.36) prints -18.0. Which method name belongs in the blank?

    df = spark.createDataFrame([(1, 12), (10, 1), (19, 8)], ["c1", "c2"])
    df. ? ("c1", "c2")
    # -18.0

    Sources4

    4.The corr aggregate in SQL

    In Databricks SQL and Databricks Runtime, corr(expr1, expr2) is an aggregate function that returns the Pearson coefficient as a DOUBLE. Both arguments must evaluate to numbers. It is the SQL equivalent of df.stat.corr, for teams that explore tables in a SQL editor rather than a notebook. In PySpark, pyspark.sql.functions.corr provides the same aggregate as a column expression you can use inside df.agg(...).

    Because it is an aggregate, it can do three things the DataFrame method cannot:

    • DISTINCT computes the coefficient over unique (expr1, expr2) pairs only, so repeated rows count once.
    • FILTER (WHERE cond) limits which rows go into the calculation, without adding a WHERE to the whole query.
    • An OVER clause runs it as a window function, giving one correlation per partition.
    The duplicated (3, 3) row changes the result once DISTINCT removes itsql
    > SELECT corr(c1, c2) FROM VALUES (3, 2), (3, 3), (3, 3), (6, 4) as tab(c1, c2);
     0.816496580927726
    
    > SELECT corr(DISTINCT c1, c2) FROM VALUES (3, 2), (3, 3), (3, 3), (6, 4) as tab(c1, c2);
     0.8660254037844387

    Checkpoint 4 of 9· Check yourself

    In a Databricks SQL editor, an analyst wants to know if two string columns, customer_segment and preferred_channel, are related. They write SELECT corr(customer_segment, preferred_channel) FROM customers. What is wrong with this approach?

    Sources56

    5.Contingency tables with df.stat.crosstab

    Take two categorical columns: customer_segment (Budget, Value, Premium, Luxury) and preferred_channel (Online, In-Store, Mobile App). Their values cannot be multiplied or averaged, so correlation has nothing to work with. What you can do is count. df.stat.crosstab("col1", "col2"), which you can also call as df.crosstab, returns a pair-wise frequency table, also called a contingency table.

    A contingency table of c1 against c2python
    df = spark.createDataFrame([(1, 11), (1, 11), (3, 10), (4, 8), (4, 8)], ["c1", "c2"])
    df.stat.crosstab("c1", "c2").sort("c1_c2").show()
    # +-----+---+---+---+
    # |c1_c2| 10| 11|  8|
    # +-----+---+---+---+
    # |    1|  0|  2|  0|
    # |    3|  1|  0|  0|
    # |    4|  0|  0|  2|
    # +-----+---+---+---+

    The order of the arguments sets the layout. Each distinct value of the first column becomes a row, and each distinct value of the second column becomes a column header. The first column of the result is named after both inputs, joined with an underscore: c1_c2 here. Combinations that never occur still get a cell, with a count of zero. In the retail example, df.stat.crosstab("customer_segment", "preferred_channel") returns four rows (one per segment) and three count columns (one per channel). Its first column is called customer_segment_preferred_channel.

    The counts describe the data. A chi-square test tells you whether the pattern is real. The table might show, say, that Luxury customers cluster in In-Store. A chi-square test of independence tells you whether that pattern is a statistically significant association or just noise, and it runs on exactly these counts. Chi-square is a test for categorical columns: Databricks' own data profiling computes its chi-square statistic only for categorical columns and leaves it null for numeric ones. So for two categorical features, build the crosstab first, then run the chi-square test on the result.

    Checkpoint 5 of 9· Fill the gap

    To see how often each value of c1 occurs with each value of c2, a data scientist wants a table of pair counts instead of a single coefficient. Which df.stat method completes this sample?

    df = spark.createDataFrame([(1, 11), (1, 11), (3, 10), (4, 8), (4, 8)], ["c1", "c2"])
    df.stat. ? ("c1", "c2").sort("c1_c2").show()
    # +-----+---+---+---+
    # |c1_c2| 10| 11|  8|
    # +-----+---+---+---+
    # |    1|  0|  2|  0|
    # |    3|  1|  0|  0|
    # |    4|  0|  0|  2|
    # +-----+---+---+---+

    Checkpoint 6 of 9· Exam question

    A data science team at a retail company has a Spark DataFrame with two categorical columns, customer_segment (Budget, Value, Premium, Luxury) and preferred_channel (Online, In-Store, Mobile App). They want to determine whether a statistically significant association exists between which segment a customer belongs to and which channel they prefer. Which approach should they use?

    Sources789

    6.Why the other methods fail these comparisons

    Most wrong answers here take a valid tool and apply it to the wrong kind of column. Each of these mismatches goes wrong in a predictable way.

    Correlation on string columns. The SQL corr aggregate requires both arguments to evaluate to a number, and df.stat.corr also works on numeric columns. Raw strings such as "Budget" and "Online" give it nothing to compute. Turning the categories into index numbers first does not help either. If segments are numbered 0 to 3, the numbers imply an order and equal spacing that the categories never had.

    A contingency table of continuous columns. Every distinct value becomes its own row or column, so a crosstab of two continuous columns is a huge grid that is mostly zeros and ones. A chi-square test on that grid tells you nothing useful about the linear trend that correlation captures in one number.

    Three more near-misses compute something real, but none of it compares two features:

    • df.describe(...) and df.summary() report count, mean, standard deviation, min and max for each column separately, with no value for the pair. See summary statistics on a Spark DataFrame.
    • df.groupBy("engine_size").agg({"fuel_consumption": "mean"}) gives the average of one column for each value of the other. That is a table of means, not a correlation.
    • One-hot encoding turns a categorical column into indicator columns for use as model input. Applied to two continuous columns, it creates one indicator per distinct value and tells you nothing about how the two columns relate.
    Matching the method to the column pair
    Column pairUseNot thisWhy not
    Two continuouscorr (Pearson)crosstabOne column per distinct value; counts of 0 or 1
    Two continuouscorr (Pearson)covMagnitude depends on the units of the columns
    Two categoricalcrosstab, then chi-squarecorrRequires numeric inputs

    Checkpoint 7 of 9· Match them up

    Each call below uses the wrong tool for the column pair it is given. Pair each call with the reason it does not compare the two features properly.

    Tap a term, then the definition that fits it.

    Checkpoint 8 of 9· Exam question

    A real estate analytics team has a Spark DataFrame containing two continuous numeric columns, square_footage and sale_price, for thousands of home sales. They want to quantify the strength and direction of the linear relationship between these two features. Which method is appropriate?

    Checkpoint 9 of 9· Exam question

    A machine learning engineer is working with a native PySpark DataFrame df that has two numeric columns, engine_size and fuel_consumption, and wants to compute the Pearson correlation coefficient between them without converting to pandas. Which method call accomplishes this?

    Sources58

    Practise it for real

    In a notebook, compare a numeric pair with corr and cov, then build a contingency table with crosstab

    1. 1.Create df = spark.createDataFrame([(1, 12), (10, 1), (19, 8)], ["c1", "c2"]) and run df.stat.corr("c1", "c2").

      Why: Shows the Pearson coefficient for two numeric columns, computed directly on a Spark DataFrame.

      You should see: -0.3592106040535498

    2. 2.On the same DataFrame, run df.cov("c1", "c2").

      Why: Puts covariance next to correlation for the same data, so you can see the difference in scale.

      You should see: -18.0

    3. 3.Create df = spark.createDataFrame([(1, 11), (1, 11), (3, 10), (4, 8), (4, 8)], ["c1", "c2"]) and run df.stat.crosstab("c1", "c2").sort("c1_c2").show().

      Why: Produces a contingency table whose rows are the distinct c1 values and whose columns are the distinct c2 values.

      You should see: A c1_c2 column with rows 1, 3 and 4, and count columns 10, 11 and 8. Row 1 has 2 under 11, row 3 has 1 under 10, row 4 has 2 under 8, and every other cell is 0.

    Stuck? Get a nudge

    If the crosstab columns appear in a different order, that only affects the display. What matters is the count for each pair.

    Sources

    (9)

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

    1. 1.
      “Computes a pair-wise frequency table of the given columns.”
      ↩︎ Choosing a comparison by feature type
      “Calculates the correlation of two columns as a double value. Currently only supports the Pearson Correlation Coefficient.”
      ↩︎ Choosing a comparison by feature type
    2. 2.
      “Currently only supports the Pearson Correlation Coefficient. DataFrame.corr and DataFrameStatFunctions.corr are aliases of each other.”
      ↩︎ Pearson correlation with df.stat.corr
      “The correlation method. Currently only supports "pearson".”
      ↩︎ Exam trap 4
      “method | str, optional | The correlation method. Currently only supports "pearson".”
      ↩︎ Checkpoint
    3. 4.
      “Calculate the sample covariance for the given columns, specified by their names, as a double value.”
      ↩︎ Covariance is a different, scale-dependent number
      “Calculate the sample covariance for the given columns, specified by their names, as a double value.”
      ↩︎ Exam trap 2
    4. 5.
      “If DISTINCT is specified the function operates only on a unique set of expr1, expr2 pairs.”
      ↩︎ The corr aggregate in SQL
      “This function can also be invoked as a window function using the OVER clause.”
      ↩︎ The corr aggregate in SQL
      “expr1: An expression that evaluates to a numeric.”
      ↩︎ Why the other methods fail these comparisons
      “Returns Pearson coefficient of correlation between a group of number pairs.”
      ↩︎ Key concept
      “expr1: An expression that evaluates to a numeric.”
      ↩︎ Exam trap 1
      “expr1: An expression that evaluates to a numeric.”
      ↩︎ Checkpoint
    5. 6.
      “Returns a new Column for the Pearson Correlation Coefficient for col1 and col2.”
      ↩︎ The corr aggregate in SQL
    6. 7.
      “Computes a pair-wise frequency table of the given columns, also known as a contingency table.”
      ↩︎ Contingency tables with df.stat.crosstab
    7. 8.
      “Pairs that have no occurrences will have zero as their counts.”
      ↩︎ Contingency tables with df.stat.crosstab
      “Distinct items will make the column names of the DataFrame.”
      ↩︎ Why the other methods fail these comparisons
      “The first column of each row will be the distinct values of col1 and the column names will be the distinct values of col2.”
      ↩︎ Exam trap 3
      “Computes a pair-wise frequency table of the given columns. Also known as a contingency table.”
      ↩︎ Checkpoint
      “The first column of each row will be the distinct values of col1 and the column names will be the distinct values of col2.”
      ↩︎ Checkpoint
    8. 9.
      “Chi-square test for drift in distribution. Calculated for categorical columns only. null for numeric columns.”
      ↩︎ Contingency tables with df.stat.crosstab

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