Skip to content

Adds triangular option to DataFrame.corr, closes #22840 #22842

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 9 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ New features
the user to override the engine's default behavior to include or omit the
dataframe's indexes from the resulting Parquet file. (:issue:`20768`)
- :meth:`DataFrame.corr` and :meth:`Series.corr` now accept a callable for generic calculation methods of correlation, e.g. histogram intersection (:issue:`22684`)
- :meth:`DataFrame.corr` now accepts a boolean argument indicating whether or not the lower triangular correlation matrix should be returned (:issue:`22840`)


.. _whatsnew_0240.enhancements.extension_array_operators:
Expand Down
16 changes: 14 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6667,7 +6667,7 @@ def _series_round(s, decimals):
# ----------------------------------------------------------------------
# Statistical methods, etc.

def corr(self, method='pearson', min_periods=1):
def corr(self, method='pearson', min_periods=1, tri=False):
"""
Compute pairwise correlation of columns, excluding NA/null values

Expand All @@ -6686,6 +6686,10 @@ def corr(self, method='pearson', min_periods=1):
to have a valid result. Currently only available for pearson
and spearman correlation

tri : boolean, default : False
Whether or not to return the lower triangular correlation
matrix

Copy link
Member

Choose a reason for hiding this comment

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

Can you add a versionadded directive here?

Returns
-------
y : DataFrame
Expand Down Expand Up @@ -6741,7 +6745,15 @@ def corr(self, method='pearson', min_periods=1):
"'spearman', or 'kendall', '{method}' "
"was supplied".format(method=method))

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

if tri:
mask = np.tril(np.ones_like(corr_mat,
Copy link
Member

Choose a reason for hiding this comment

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

Is it possible to use correl instead of corr_mat here to avoid the conversion hit of DataFrame to numpy array when np.ones_like is called? (I think correl should be a numpy array here)

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, nice catch. correl should already be a numpy array.

dtype=np.bool),
k=-1)
return corr_mat.where(mask)
else:
return corr_mat

def cov(self, min_periods=None):
"""
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/frame/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ def test_corr_invalid_method(self):
with tm.assert_raises_regex(ValueError, msg):
df.corr(method="____")

def test_corr_tri(self):
# GH PR
Copy link
Member

Choose a reason for hiding this comment

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

This should reference this issue number (22840)

df = pd.DataFrame(np.random.normal(size=(100, 5)))
corr_mat = df.corr(tri=True)
assert corr_mat.notnull().sum().sum() == 10

def test_cov(self):
# min_periods no NAs (corner case)
expected = self.frame.cov()
Expand Down