Skip to content

Add option for alternative correlation types to DataFrame.corrwith() #21941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6891,7 +6891,7 @@ def cov(self, min_periods=None):

return self._constructor(baseCov, index=idx, columns=cols)

def corrwith(self, other, axis=0, drop=False):
def corrwith(self, other, axis=0, method='pearson', drop=False):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm...it would be safest to add it to the end of the signature, as this modification as it stands is not backwards compatible. Alternatively, you could issue a DeprecationWarning if a boolean is passed to method and re-assign it to drop.

"""
Compute pairwise correlation between rows or columns of two DataFrame
objects.
Expand All @@ -6901,6 +6901,10 @@ def corrwith(self, other, axis=0, drop=False):
other : DataFrame, Series
axis : {0 or 'index', 1 or 'columns'}, default 0
0 or 'index' to compute column-wise, 1 or 'columns' for row-wise
method : {'pearson', 'kendall', 'spearman'}
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation
drop : boolean, default False
Drop missing indices from result, default returns union of all

Expand All @@ -6912,10 +6916,9 @@ def corrwith(self, other, axis=0, drop=False):
this = self._get_numeric_data()

if isinstance(other, Series):
return this.apply(other.corr, axis=axis)
return this.apply(other.corr, axis=axis, method=method)

other = other._get_numeric_data()

left, right = this.align(other, join='inner', copy=False)

# mask missing values
Expand All @@ -6926,14 +6929,9 @@ def corrwith(self, other, axis=0, drop=False):
left = left.T
right = right.T

# demeaned data
ldem = left - left.mean()
rdem = right - right.mean()

num = (ldem * rdem).sum()
dom = (left.count() - 1) * left.std() * right.std()

correl = num / dom
correl = Series(index=left.columns)
for col in left.columns:
correl[col] = nanops.nancorr(left[col], right[col], method=method)

if not drop:
raxis = 1 if axis == 0 else 0
Expand Down