Skip to content

PERF: faster corrwith method for pearson and spearman correlation when other is a Series and axis = 0 (column-wise) #46174

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

Merged
merged 14 commits into from
Mar 3, 2022
Merged
22 changes: 21 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9838,7 +9838,27 @@ def corrwith(self, other, axis: Axis = 0, drop=False, method="pearson") -> Serie
this = self._get_numeric_data()

if isinstance(other, Series):
return this.apply(lambda x: other.corr(x, method=method), axis=axis)
if axis == 0 and method in ["pearson", "spearman"]:
corrs = {}
numeric_cols = self.select_dtypes(include=np.number).columns
ndf = self[numeric_cols].values.transpose()
k = other.values
if method == "pearson":
for i, r in enumerate(ndf):
nonnull_mask = ~np.isnan(r) & ~np.isnan(k)
corrs[numeric_cols[i]] = np.corrcoef(
r[nonnull_mask], k[nonnull_mask]
)[0, 1]
else:
for i, r in enumerate(ndf):
nonnull_mask = ~np.isnan(r) & ~np.isnan(k)
corrs[numeric_cols[i]] = np.corrcoef(
r[nonnull_mask].argsort().argsort(),
k[nonnull_mask].argsort().argsort(),
)[0, 1]
return Series(corrs)
else:
return this.apply(lambda x: other.corr(x, method=method), axis=axis)

other = other._get_numeric_data()
left, right = this.align(other, join="inner", copy=False)
Expand Down