Skip to content

Bug:DataFrame index & column returned by corr & cov are the same (#14617) #15528

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ Bug Fixes


- Bug in ``.rank()`` which incorrectly ranks ordered categories (:issue:`15420`)

- Bug in ``.corr()`` and ``.cov()`` where the column and index were the same object (:issue:`14617`)


- Require at least 0.23 version of cython to avoid problems with character encodings (:issue:`14699`)
Expand Down
6 changes: 4 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4725,6 +4725,7 @@ def corr(self, method='pearson', min_periods=1):
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values

if method == 'pearson':
Expand Down Expand Up @@ -4757,7 +4758,7 @@ def corr(self, method='pearson', min_periods=1):
correl[i, j] = c
correl[j, i] = c

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

def cov(self, min_periods=None):
"""
Expand All @@ -4780,6 +4781,7 @@ def cov(self, min_periods=None):
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values

if notnull(mat).all():
Expand All @@ -4793,7 +4795,7 @@ def cov(self, min_periods=None):
baseCov = _algos.nancorr(_ensure_float64(mat), cov=True,
minp=min_periods)

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

def corrwith(self, other, axis=0, drop=False):
"""
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ def test_corr_int_and_boolean(self):
for meth in ['pearson', 'kendall', 'spearman']:
tm.assert_frame_equal(df.corr(meth), expected)

def test_corr_cov_independent_index_column(self):
# GH 14617
df = pd.DataFrame(np.random.randn(4 * 10).reshape(10, 4),
columns=list("abcd"))
for method in ['cov', 'corr']:
result = getattr(df, method)()
self.assertFalse(result.index is result.columns)

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