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 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
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 an argument indicating whether or not a triangular correlation matrix should be returned (:issue:`22840`)


.. _whatsnew_0240.enhancements.extension_array_operators:
Expand Down
35 changes: 33 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=None):
"""
Compute pairwise correlation of columns, excluding NA/null values

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

tri : {'upper', 'lower'} or None, default : None
Whether or not to return the upper / lower triangular
correlation matrix. (This is useful for example when
one wishes to easily identify highly collinear columns
in a DataFrame.)

.. versionadded:: 0.24.0

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 All @@ -6701,6 +6709,13 @@ def corr(self, method='pearson', min_periods=1):
dogs cats
dogs 1.0 0.3
cats 0.3 1.0
>>> df = pd.DataFrame(np.random.normal(size=(10, 2)))
>>> df[2] = df[0]
>>> df.corr(tri='lower').where(lambda x: x == 1)
0 1 2
0 NaN NaN NaN
1 NaN NaN NaN
2 1.0 NaN NaN
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
Expand Down Expand Up @@ -6741,7 +6756,23 @@ 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 is not None:
mask = np.tril(np.ones_like(correl,
dtype=np.bool),
k=-1)

if tri == 'lower':
return corr_mat.where(mask)
Copy link
Contributor

Choose a reason for hiding this comment

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

Not the speed is probably important, but corr+np.tril(corr*np.nan) is probably faster than indexing.

elif tri == 'upper':
return corr_mat.where(mask.T)
else:
raise ValueError("tri must be either 'lower', "
"or 'upper', '{tri_method}' "
"was supplied".format(tri_method=tri))
else:
return corr_mat

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

def test_corr_tril(self):
Copy link
Member

Choose a reason for hiding this comment

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

For these tests, it's better to build an expected DataFrame output and compare it to a resulting DataFrame. You can build a DataFrame that gives a trivial correlation matrix (like a np.ones DataFrame)

result = df.corr(tri=...)
expected = pd.DataFrame(...)
tm.assert_frame_equal(result, expected)

Copy link
Member Author

@dsaxton dsaxton Sep 26, 2018

Choose a reason for hiding this comment

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

I updated the tests according to this idea. We're still using DataFrames inside ones_like, but I figured this is okay since they're small test cases.

# GH PR #22840
df = pd.DataFrame(np.array([np.arange(100)] * 5).T)
result = df.corr(tri='lower')
mask = np.tril(np.ones_like(result,
dtype=np.bool),
k=-1)
expected = pd.DataFrame(np.ones_like(result)).where(mask)
tm.assert_frame_equal(result, expected)

def test_corr_triu(self):
# GH PR #22840
df = pd.DataFrame(np.array([np.arange(100)] * 5).T)
result = df.corr(tri='upper')
mask = np.triu(np.ones_like(result,
dtype=np.bool),
k=1)
expected = pd.DataFrame(np.ones_like(result)).where(mask)
tm.assert_frame_equal(result, expected)

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