import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [4, 3, 2, 1]
})
target_series = pd.Series([10, 20, 30, 40])
print(df.corrwith(target_series))
Expected Output:
A 1.0
B -1.0
dtype: float64
The DataFrame.corrwith() method computes pairwise correlation coefficients between columns (or rows) of a DataFrame and another Series or DataFrame object. While the standard df.corr() method generates an entire square $N imes N$ correlation matrix containing all internal column-to-column pairs, corrwith() evaluates direct correlation against a target baseline Series (such as stock market benchmark indexes, target ML labels, or macro-economic indicators).
DataFrame.corrwith(other, axis=0, drop=False, method='pearson', numeric_only=False)other: Series or DataFrame to compute correlation against.axis: 0 or 'index' (compute correlation column-by-column; default), 1 or 'columns' (compute correlation row-by-row).drop: Boolean (default False). Drops missing values before computing correlation.method: 'pearson' (standard correlation), 'spearman' (rank correlation), or 'kendall' (ordinal rank correlation).numeric_only: Boolean (default False). Restricts analysis to numeric columns.Use non-parametric rank correlation (method='spearman') to evaluate non-linear monotonic relationships.
import pandas as pd
df_features = pd.DataFrame({
'Spend': [100, 200, 500, 1000],
'Clicks': [10, 25, 40, 45]
})
y_sales = pd.Series([15, 30, 75, 150])
# Compute Spearman rank correlation
corr_spearman = df_features.corrwith(y_sales, method='spearman')
print(corr_spearman)
Expected Output:
Spend 1.0
Clicks 1.0
dtype: float64
NaN values.corrwith().
Q: How does corrwith() differ from corr()?
df.corr() computes pairwise correlations across all columns inside a single DataFrame (returning a square matrix). df.corrwith(other) computes correlation between columns of `df` and an external target Series or DataFrame (returning a 1D Series).
Explore interactive code cells, test Spearman rank correlations, and execute self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.