Skip to content
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

Restrict clipping of DataFrame.corr only when cov=False #61214

Merged
merged 17 commits into from
Apr 3, 2025
Merged
Show file tree
Hide file tree
Changes from 16 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
9 changes: 5 additions & 4 deletions pandas/_libs/algos.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -391,10 +391,11 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None):
# clip `covxy / divisor` to ensure coeff is within bounds
if divisor != 0:
val = covxy / divisor
if val > 1.0:
val = 1.0
elif val < -1.0:
val = -1.0
if not cov:
if val > 1.0:
val = 1.0
elif val < -1.0:
val = -1.0
result[xi, yi] = result[yi, xi] = val
else:
result[xi, yi] = result[yi, xi] = NaN
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/frame/methods/test_cov_corr.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,9 @@ def test_corr_within_bounds(self):
corr_matrix = df2.corr()
assert corr_matrix.min().min() >= -1.0
assert corr_matrix.max().max() <= 1.0

def test_cov_with_missing_values(self):
df = DataFrame({"A": [1, 2, None, 4], "B": [2, 4, None, 9]})
expected = DataFrame({"A": [1.0, 1.0], "B": [1.0, 1.0]})
Copy link
Contributor

Choose a reason for hiding this comment

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

Looks like the the expected dataframe needs index=["A", "B"]: https://github.com/pandas-dev/pandas/actions/runs/14250783260/job/39942795933?pr=61214#step:5:45

And can you confirm that 1 is the expected value? If the 2.2.3 behavior is correct, then the values in #61154 (comment) were different:

Out[68]:
          A     B
A  2.333333   5.5
B  5.500000  13.0

I don't know whether it matters, but it might be worth testing both df.cov() and df.dropna().cov()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixing now. Thanks!

result = df.dropna().cov()
tm.assert_frame_equal(result, expected)
Loading