Skip to content
Merged
3 changes: 3 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -11233,6 +11233,9 @@ def corr(
f"'{method}' was supplied"
)

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

result = self._constructor(correl, index=idx, columns=cols, copy=False)
return result.__finalize__(self, method="corr")

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