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.
| Method | Suited to | Returns | What it tells you |
|---|---|---|---|
| corr(col1, col2, method) | Two continuous columns | A double | Strength and direction of the linear relationship (Pearson only) |
| cov(col1, col2) | Two continuous columns | A double | Sample covariance, in the units of the two columns |
| crosstab(col1, col2) | Two categorical columns | A DataFrame | Pair-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.
corr and cov both reduce two numeric columns to one double. Only corr gives the unit-free Pearson coefficient; cov stays in the columns' units. crosstab is the method for two categorical columns, and it returns a whole contingency table of pair counts instead of a single number.
“Computes a pair-wise frequency table of the given columns. Also known as a contingency table.”Source: docs.databricks.com
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.
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.0The 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?
df.stat.corr computes only the Pearson coefficient. Its method parameter accepts only "pearson", and df.corr is just an alias for the same method, so neither one has a rank-based alternative.
“method | str, optional | The correlation method. Currently only supports "pearson".”Source: docs.databricks.com
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.
df = spark.createDataFrame([(1, 12), (10, 1), (19, 8)], ["c1", "c2"])
df.cov("c1", "c2")
# -18.0The 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-18.0 is outside the -1 to 1 range, so it cannot be a Pearson coefficient. crosstab returns a DataFrame of counts, not one double. cov returns the sample covariance in the columns' multiplied units, so its size alone does not show how strong the relationship is.
Source: docs.databricks.comSources4
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:
DISTINCTcomputes 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 aWHEREto the whole query.- An
OVERclause runs it as a window function, giving one correlation per partition.
> 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.8660254037844387The pair (3, 3) appears twice. Plain corr uses all four rows. corr(DISTINCT ...) drops the duplicate and computes over three unique pairs, which moves the result from about 0.817 to about 0.866.
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?
The SQL corr aggregate returns a Pearson coefficient for pairs of numbers, and each argument must evaluate to a numeric value. DISTINCT and OVER only change which rows go into that numeric calculation. Neither one makes string categories usable. Two categorical columns are compared by counting how often each pair of values occurs together.
“expr1: An expression that evaluates to a numeric.”Source: docs.databricks.com
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.
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|
# +-----+---+---+---+Only crosstab returns a DataFrame: a contingency table with one row per distinct c1 value, one column per distinct c2 value, and zero counts for pairs that never occur. corr and cov each return a single double, so you could not call .sort().show() on their result.
Source: docs.databricks.comCheckpoint 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?
Correct answer: A — Build a contingency table cross-tabulating customer_segment against preferred_channel, then run a chi-square test of independence on the counts.
- A. Cross-tabulating two categorical columns produces the observed frequency counts that a chi-square test of independence compares against the counts expected under no association. This is the standard method for testing whether two categorical features are related.
- B. Pearson correlation requires numeric, ordered values and quantifies a linear relationship; string category labels like segment names have no inherent numeric order, so computing a correlation on them directly is not meaningful.
- C. ANOVA compares the mean of a continuous variable across groups defined by a categorical variable. Neither
customer_segmentnorpreferred_channelis continuous, so there is no numeric outcome for ANOVA to compare means of. - D. Linear regression models a continuous response as a function of predictors.
customer_segmentis a categorical label, not a continuous quantity, so it cannot serve as the response variable in this setup.
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(...)anddf.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.
| Column pair | Use | Not this | Why not |
|---|---|---|---|
| Two continuous | corr (Pearson) | crosstab | One column per distinct value; counts of 0 or 1 |
| Two continuous | corr (Pearson) | cov | Magnitude depends on the units of the columns |
| Two categorical | crosstab, then chi-square | corr | Requires 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.
crosstab does no binning, so continuous columns turn into one row or column per distinct value. corr needs numeric inputs, cov is measured in the columns' units, and a grouped mean only lists averages. For two continuous columns the right tool is Pearson corr. For two categorical columns it is crosstab followed by chi-square.
“The first column of each row will be the distinct values of col1 and the column names will be the distinct values of col2.”Source: docs.databricks.com
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?
Correct answer: A — Compute the Pearson correlation coefficient between square_footage and sale_price, yielding a value between -1 and 1 summarizing the linear relationship.
- A. The Pearson correlation coefficient is the standard measure for the strength and direction of a linear relationship between two continuous features, expressed as a single value from -1 to 1. It directly answers what this team is asking about
square_footageandsale_price. - B. A contingency table and chi-square test are built for two categorical features with a finite set of category values. Applying them to continuous, near-unique numeric columns like square footage and price does not produce a meaningful frequency table.
- C. Binning both continuous columns and comparing means throws away the granularity of both features and answers a different question than the strength of their linear relationship; a t-test also assumes only two groups, not a full continuous relationship.
- D. One-hot encoding is meant for categorical features with a small number of distinct labels, not continuous measurements like square footage and price. Encoding these columns this way would create an unmanageable number of indicator columns and would not measure a linear relationship.
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?
Correct answer: A — df.stat.corr("engine_size", "fuel_consumption") returns the Pearson correlation coefficient computed directly on the two numeric columns.
- A. The
stat.corrmethod on a PySpark DataFrame computes the Pearson correlation coefficient between two named numeric columns without requiring a conversion to pandas. This is exactly the built-in method for this task. - B.
stat.crosstabbuilds a contingency table of co-occurrence counts, which is the tool for comparing two categorical columns, not for computing a correlation coefficient between two continuous columns. - C.
describereports per-column summary statistics like mean and standard deviation independently for each column, but it does not compute any measure of the relationship between two columns. - D. Grouping by one column and aggregating the mean of another produces conditional averages, not a correlation coefficient, and it treats the grouping column as if it were categorical rather than measuring a linear relationship between two continuous features.
Practise it for real
In a notebook, compare a numeric pair with corr and cov, then build a contingency table with crosstab
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.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.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.
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframestatfunctions/corrOfficial docs
“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.
“float: Pearson Correlation Coefficient of two columns.”
↩︎ Pearson correlation with df.stat.corr - 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 - 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 - 6.
“Returns a new Column for the Pearson Correlation Coefficient for col1 and col2.”
↩︎ The corr aggregate in SQL - 7.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframestatfunctions/crosstabOfficial docs
“Computes a pair-wise frequency table of the given columns, also known as a contingency table.”
↩︎ Contingency tables with df.stat.crosstab - 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 - 9.
“Chi-square test for drift in distribution. Calculated for categorical columns only. null for numeric columns.”
↩︎ Contingency tables with df.stat.crosstab