Skip to content
Merged
3 changes: 3 additions & 0 deletions pandas/_libs/algos.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None):
else:
result[xi, yi] = result[yi, xi] = NaN

# clip coefficient to ensure it is within theoretical bounds
result = np.clip(result, -1, 1)

return result.base

# ----------------------------------------------------------------------
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/methods/test_cov_corr.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,3 +485,15 @@ def test_corrwith_min_periods_boolean(self):
result = df_bool.corrwith(ser_bool, min_periods=3)
expected = Series([0.57735, 0.57735], index=["A", "B"])
tm.assert_series_equal(result, expected)

def test_corr_within_bounds(self):
df1 = DataFrame({"x": [0, 1], "y": [1.35951, 1.3595100000000007]})
result1 = df1.corr().max().max()
expected1 = 1.0
tm.assert_equal(result1, expected1)

rng = np.random.default_rng(seed=42)
df2 = DataFrame(rng.random((100, 4)))
corr_matrix = df2.corr()
assert corr_matrix.min().min() >= -1.0
assert corr_matrix.max().max() <= 1.0
Loading