From 1f8c6280cb9203eb28b0378b76569ddf591afe44 Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Thu, 23 Oct 2025 10:46:48 +0000 Subject: [PATCH 1/8] init commit kendall spearman ordinal cats --- pandas/core/frame.py | 27 +++++++++++++++++- pandas/core/series.py | 6 ++++ pandas/tests/series/methods/test_cov_corr.py | 29 +++++++++++++++++++- test_corr.py | 23 ++++++++++++++++ 4 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 test_corr.py diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d4ff1bc4f35ac..44d13c6e81641 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11633,6 +11633,11 @@ def corr( data = self._get_numeric_data() if numeric_only else self cols = data.columns idx = cols.copy() + + if method in ("spearman", "kendall"): + data = data._transform_ord_cat_cols_to_coded_cols() + + mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False) if method == "pearson": @@ -11926,7 +11931,8 @@ def corrwith( correl = num / dom elif method in ["kendall", "spearman"] or callable(method): - + left = left._convert_ordered_cat_to_code() + right = right._convert_ordered_cat_to_code() def c(x): return nanops.nancorr(x[0], x[1], method=method) @@ -11957,6 +11963,25 @@ def c(x): return correl + def _transform_ord_cat_cols_to_coded_cols(self) -> DataFrame: + """ + any ordered categorical columns are transformed to the respectice caregorical codes + other columns remain untouched + """ + categ = self.select_dtypes("category") + if len(categ.columns) == 0: + return self + + cols_convert = categ.loc[:, categ.agg(lambda x: x.cat.ordered)].columns + + if len(cols_convert) > 0: + data = self.copy(deep=False) + data[cols_convert] = data[cols_convert].transform( + lambda x: x.cat.codes.replace(-1, np.nan) + ) + return data + return self + # ---------------------------------------------------------------------- # ndarray-like stats methods diff --git a/pandas/core/series.py b/pandas/core/series.py index f3aaee26fe470..dd7d6a513ecf2 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2687,6 +2687,12 @@ def corr( this, other = self.align(other, join="inner") if len(this) == 0: return np.nan + + if method in ("spearman", "kendall"): + if this.dtype == "category" and this.cat.ordered: + this = this.cat.codes.replace(-1, np.nan) + if other.dtype == "category" and other.cat.ordered: + other = other.cat.codes.replace(-1, np.nan) this_values = this.to_numpy(dtype=float, na_value=np.nan, copy=False) other_values = other.to_numpy(dtype=float, na_value=np.nan, copy=False) diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index 7a4d48fb76940..322bbfdd884c7 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -11,7 +11,6 @@ ) import pandas._testing as tm - class TestSeriesCov: def test_cov(self, datetime_series): # full overlap @@ -184,3 +183,31 @@ def test_corr_callable_method(self, datetime_series): df = pd.DataFrame([s1, s2]) expected = pd.DataFrame([{0: 1.0, 1: 0}, {0: 0, 1: 1.0}]) tm.assert_almost_equal(df.transpose().corr(method=my_corr), expected) + + @pytest.mark.parametrize("method", ["kendall", "spearman"]) + def test_corr_rank_ordered_categorical(self, method,): + stats = pytest.importorskip("scipy.stats") + method_scipy_func = { + "kendall": stats.kendalltau, + "spearman": stats.spearmanr + } + ser_ord_cat = pd.Series( pd.Categorical( + ["low", "m", "h", "vh"], + categories=["low", "m", "h", "vh"], ordered=True + )) + ser_ord_cat_codes = ser_ord_cat.cat.codes.replace(-1, np.nan) + ser_ord_int = pd.Series([0, 1, 2, 3]) + ser_ord_float = pd.Series([2.0, 3.0, 4.5, 6.5]) + + corr_calc = ser_ord_cat.corr(ser_ord_int, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_int)[0] + tm.assert_almost_equal(corr_calc, corr_expected) + + corr_calc = ser_ord_cat.corr(ser_ord_float, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_float)[0] + tm.assert_almost_equal(corr_calc, corr_expected) + + corr_calc = ser_ord_cat.corr(ser_ord_cat, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_cat_codes)[0] + tm.assert_almost_equal(corr_calc, corr_expected) + diff --git a/test_corr.py b/test_corr.py new file mode 100644 index 0000000000000..e52674647ef1b --- /dev/null +++ b/test_corr.py @@ -0,0 +1,23 @@ +import pandas as pd +df = pd.DataFrame({'a' : [1, 2, 3, 4], 'b' : [4, 3, 2, 1]}) +df['b'] = df['b'].astype('category').cat.set_categories([4, 3, 2, 1], ordered=True) +#import pdb; pdb.set_trace() +crr = df.corr(method='spearman') +print(crr) + + +df = pd.DataFrame({'a' : [1, 2, 3, 4], 'b' : ["vh", "h", "m", "l"]}) +df['b'] = df['b'].astype('category').cat.set_categories(["vh", "h", "m", "l"], ordered=True) +#import pdb; pdb.set_trace() +print(df) +print(df.dtypes) +crr = df.corr(method='spearman') +print(crr) + +ser_ord_cat = pd.Series( pd.Categorical( + ["vh", "h", "m", "low"], + categories=["vh", "h", "m", "low"], ordered=True + )) +print(ser_ord_cat) +crr = ser_ord_cat.corr(ser_ord_cat, method='spearman') +print(crr) \ No newline at end of file From 497dc7e88a418b99a07a02b841a63941d986cc1a Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Mon, 27 Oct 2025 11:31:35 +0000 Subject: [PATCH 2/8] series test update and fixes --- pandas/core/frame.py | 4 +-- pandas/tests/series/methods/test_cov_corr.py | 29 ++++++++++++++++++-- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0a9ae652bca71..d202d4db0e9c5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11964,8 +11964,8 @@ def corrwith( correl = num / dom elif method in ["kendall", "spearman"] or callable(method): - left = left._convert_ordered_cat_to_code() - right = right._convert_ordered_cat_to_code() + left = left._transform_ord_cat_cols_to_coded_cols() + right = right._transform_ord_cat_cols_to_coded_cols() def c(x): return nanops.nancorr(x[0], x[1], method=method) diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index 322bbfdd884c7..c4b16224cc19c 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -200,14 +200,37 @@ def test_corr_rank_ordered_categorical(self, method,): ser_ord_float = pd.Series([2.0, 3.0, 4.5, 6.5]) corr_calc = ser_ord_cat.corr(ser_ord_int, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_int)[0] + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_int, nan_policy="omit")[0] tm.assert_almost_equal(corr_calc, corr_expected) corr_calc = ser_ord_cat.corr(ser_ord_float, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_float)[0] + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_float, nan_policy="omit")[0] tm.assert_almost_equal(corr_calc, corr_expected) corr_calc = ser_ord_cat.corr(ser_ord_cat, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_cat_codes)[0] + corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_cat_codes, nan_policy="omit")[0] tm.assert_almost_equal(corr_calc, corr_expected) + + ser_ord_cat_shuff = pd.Series( pd.Categorical( + ["h", "low", "vh", "m"], + categories=["low", "m", "h", "vh"], ordered=True + )) + ser_ord_cat_shuff_codes = ser_ord_cat_shuff.cat.codes.replace(-1, np.nan) + corr_calc = ser_ord_cat_shuff.corr(ser_ord_cat, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_shuff_codes, ser_ord_cat_codes, nan_policy="omit")[0] + tm.assert_almost_equal(corr_calc, corr_expected) + + corr_calc = ser_ord_cat_shuff.corr(ser_ord_cat_shuff, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_shuff_codes, ser_ord_cat_shuff_codes, nan_policy="omit")[0] + tm.assert_almost_equal(corr_calc, corr_expected) + + ser_ord_cat_with_nan = pd.Series( pd.Categorical( + ["h", "low", "vh", None, "m"], + categories=["low", "m", "h", "vh"], ordered=True + )) + ser_ord_cat_shuff_with_nan_codes = ser_ord_cat_with_nan.cat.codes.replace(-1, np.nan) + ser_ord_int = pd.Series([2, 0, 1, 3, None]) + corr_calc = ser_ord_cat_with_nan.corr(ser_ord_int, method=method) + corr_expected = method_scipy_func[method](ser_ord_cat_shuff_with_nan_codes, ser_ord_int, nan_policy="omit")[0] + tm.assert_almost_equal(corr_calc, corr_expected) \ No newline at end of file From 583aca6d3a3decbb6054b6343f2ce83d83f879c1 Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Mon, 27 Oct 2025 11:46:42 +0000 Subject: [PATCH 3/8] cat desc longer in tests --- pandas/tests/series/methods/test_cov_corr.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index c4b16224cc19c..aa706367d38f5 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -192,8 +192,8 @@ def test_corr_rank_ordered_categorical(self, method,): "spearman": stats.spearmanr } ser_ord_cat = pd.Series( pd.Categorical( - ["low", "m", "h", "vh"], - categories=["low", "m", "h", "vh"], ordered=True + ["low", "med", "high", "very_high"], + categories=["low", "med", "high", "very_high"], ordered=True )) ser_ord_cat_codes = ser_ord_cat.cat.codes.replace(-1, np.nan) ser_ord_int = pd.Series([0, 1, 2, 3]) @@ -212,8 +212,8 @@ def test_corr_rank_ordered_categorical(self, method,): tm.assert_almost_equal(corr_calc, corr_expected) ser_ord_cat_shuff = pd.Series( pd.Categorical( - ["h", "low", "vh", "m"], - categories=["low", "m", "h", "vh"], ordered=True + ["high", "low", "very_high", "med"], + categories=["low", "med", "high", "very_high"], ordered=True )) ser_ord_cat_shuff_codes = ser_ord_cat_shuff.cat.codes.replace(-1, np.nan) From e06981087966df29ec0ace23aac68c5b08ed35a5 Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Mon, 27 Oct 2025 12:28:27 +0000 Subject: [PATCH 4/8] testing frame corr --- pandas/tests/frame/methods/test_cov_corr.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index a5ed2e86283e9..23e8c50489480 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -1,3 +1,4 @@ +from itertools import combinations import numpy as np import pytest @@ -251,6 +252,24 @@ def test_corr_numeric_only(self, meth, numeric_only): else: with pytest.raises(ValueError, match="could not convert string to float"): df.corr(meth, numeric_only=numeric_only) + + @pytest.mark.parametrize("method", ["kendall", "spearman"]) + def test_corr_rank_ordered_categorical(self, method,): + df = DataFrame( + { + "ord_cat": pd.Series(pd.Categorical(["low", "m", "h", "vh"], categories=["low", "m", "h", "vh"], ordered=True)), + "ord_cat_none": pd.Series(pd.Categorical(["low", "m", "h", None], categories=["low", "m", "h"], ordered=True)), + "ord_int": pd.Series([0, 1, 2, 3]), + "ord_float": pd.Series([2.0, 3.0, 4.5, 6.5]), + "ord_float_nan": pd.Series([2.0, 3.0, 4.5, np.nan]), + "ord_cat_shuff": pd.Series(pd.Categorical(["m", "h", "vh", "low"], categories=["low", "m", "h", "vh"], ordered=True)), + } + ) + corr_calc = df.corr(method=method) + for col1, col2 in combinations(["ord_cat", "ord_int", "ord_float"], r=2): + expected = df[col1].corr(df[col2], method=method) + tm.assert_almost_equal(corr_calc[col1][col2], expected) + class TestDataFrameCorrWith: From b90726fd73f5ce19b6f4d0ce9be5f0ebc5fe1cfc Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Mon, 27 Oct 2025 13:40:09 +0000 Subject: [PATCH 5/8] pre commit fixes v2 --- pandas/core/frame.py | 6 +- pandas/core/series.py | 2 +- pandas/tests/frame/methods/test_cov_corr.py | 92 +++++++++++++++++--- pandas/tests/series/methods/test_cov_corr.py | 88 ++++++++++++------- test_corr.py | 32 ++++--- 5 files changed, 158 insertions(+), 62 deletions(-) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d202d4db0e9c5..9b4e15ac7aac5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -11670,7 +11670,6 @@ def corr( if method in ("spearman", "kendall"): data = data._transform_ord_cat_cols_to_coded_cols() - mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False) if method == "pearson": @@ -11966,6 +11965,7 @@ def corrwith( elif method in ["kendall", "spearman"] or callable(method): left = left._transform_ord_cat_cols_to_coded_cols() right = right._transform_ord_cat_cols_to_coded_cols() + def c(x): return nanops.nancorr(x[0], x[1], method=method) @@ -11998,8 +11998,8 @@ def c(x): def _transform_ord_cat_cols_to_coded_cols(self) -> DataFrame: """ - any ordered categorical columns are transformed to the respectice caregorical codes - other columns remain untouched + any ordered categorical columns are transformed to the respective + categorical codes while other columns remain untouched """ categ = self.select_dtypes("category") if len(categ.columns) == 0: diff --git a/pandas/core/series.py b/pandas/core/series.py index 65c40244e3954..5a9c262fe699e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2686,7 +2686,7 @@ def corr( this, other = self.align(other, join="inner") if len(this) == 0: return np.nan - + if method in ("spearman", "kendall"): if this.dtype == "category" and this.cat.ordered: this = this.cat.codes.replace(-1, np.nan) diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 23e8c50489480..e56308f48e3c2 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -1,4 +1,5 @@ from itertools import combinations + import numpy as np import pytest @@ -252,24 +253,45 @@ def test_corr_numeric_only(self, meth, numeric_only): else: with pytest.raises(ValueError, match="could not convert string to float"): df.corr(meth, numeric_only=numeric_only) - + @pytest.mark.parametrize("method", ["kendall", "spearman"]) - def test_corr_rank_ordered_categorical(self, method,): + def test_corr_rank_ordered_categorical( + self, + method, + ): df = DataFrame( { - "ord_cat": pd.Series(pd.Categorical(["low", "m", "h", "vh"], categories=["low", "m", "h", "vh"], ordered=True)), - "ord_cat_none": pd.Series(pd.Categorical(["low", "m", "h", None], categories=["low", "m", "h"], ordered=True)), - "ord_int": pd.Series([0, 1, 2, 3]), - "ord_float": pd.Series([2.0, 3.0, 4.5, 6.5]), - "ord_float_nan": pd.Series([2.0, 3.0, 4.5, np.nan]), - "ord_cat_shuff": pd.Series(pd.Categorical(["m", "h", "vh", "low"], categories=["low", "m", "h", "vh"], ordered=True)), + "ord_cat": Series( + pd.Categorical( + ["low", "m", "h", "vh"], + categories=["low", "m", "h", "vh"], + ordered=True, + ) + ), + "ord_cat_none": Series( + pd.Categorical( + ["low", "m", "h", None], + categories=["low", "m", "h"], + ordered=True, + ) + ), + "ord_int": Series([0, 1, 2, 3]), + "ord_float": Series([2.0, 3.0, 4.5, 6.5]), + "ord_float_nan": Series([2.0, 3.0, 4.5, np.nan]), + "ord_cat_shuff": Series( + pd.Categorical( + ["m", "h", "vh", "low"], + categories=["low", "m", "h", "vh"], + ordered=True, + ) + ), + "ord_int_shuff": Series([2, 3, 0, 1]), } ) corr_calc = df.corr(method=method) - for col1, col2 in combinations(["ord_cat", "ord_int", "ord_float"], r=2): - expected = df[col1].corr(df[col2], method=method) - tm.assert_almost_equal(corr_calc[col1][col2], expected) - + for col1, col2 in combinations(df.columns, r=2): + corr_expected = df[col1].corr(df[col2], method=method) + tm.assert_almost_equal(corr_calc[col1][col2], corr_expected) class TestDataFrameCorrWith: @@ -512,3 +534,49 @@ def test_cov_with_missing_values(self): result2 = df.dropna().cov() tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) + + @pytest.mark.parametrize("method", ["kendall", "spearman"]) + def test_corr_rank_ordered_categorical( + self, + method, + ): + df1 = DataFrame( + { + "a": Series( + pd.Categorical( + ["low", "m", "h", "vh"], + categories=["low", "m", "h", "vh"], + ordered=True, + ) + ), + "b": Series( + pd.Categorical( + ["low", "m", "h", None], + categories=["low", "m", "h"], + ordered=True, + ) + ), + "c": Series([0, 1, 2, 3]), + "d": Series([2.0, 3.0, 4.5, 6.5]), + } + ) + + df2 = DataFrame( + { + "a": Series([2.0, 3.0, 4.5, np.nan]), + "b": Series( + pd.Categorical( + ["m", "h", "vh", "low"], + categories=["low", "m", "h", "vh"], + ordered=True, + ) + ), + "c": Series([2, 3, 0, 1]), + "d": Series([2.0, 3.0, 4.5, 6.5]), + } + ) + + corr_calc = df1.corrwith(df2, method=method) + for col in df1.columns: + corr_expected = df1[col].corr(df2[col], method=method) + tm.assert_almost_equal(corr_calc.get(col), corr_expected) diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py index aa706367d38f5..6d1f439f6ccd0 100644 --- a/pandas/tests/series/methods/test_cov_corr.py +++ b/pandas/tests/series/methods/test_cov_corr.py @@ -11,6 +11,7 @@ ) import pandas._testing as tm + class TestSeriesCov: def test_cov(self, datetime_series): # full overlap @@ -183,54 +184,77 @@ def test_corr_callable_method(self, datetime_series): df = pd.DataFrame([s1, s2]) expected = pd.DataFrame([{0: 1.0, 1: 0}, {0: 0, 1: 1.0}]) tm.assert_almost_equal(df.transpose().corr(method=my_corr), expected) - + @pytest.mark.parametrize("method", ["kendall", "spearman"]) - def test_corr_rank_ordered_categorical(self, method,): + def test_corr_rank_ordered_categorical( + self, + method, + ): stats = pytest.importorskip("scipy.stats") - method_scipy_func = { - "kendall": stats.kendalltau, - "spearman": stats.spearmanr - } - ser_ord_cat = pd.Series( pd.Categorical( - ["low", "med", "high", "very_high"], - categories=["low", "med", "high", "very_high"], ordered=True - )) + method_scipy_func = {"kendall": stats.kendalltau, "spearman": stats.spearmanr} + ser_ord_cat = Series( + pd.Categorical( + ["low", "med", "high", "very_high"], + categories=["low", "med", "high", "very_high"], + ordered=True, + ) + ) ser_ord_cat_codes = ser_ord_cat.cat.codes.replace(-1, np.nan) - ser_ord_int = pd.Series([0, 1, 2, 3]) - ser_ord_float = pd.Series([2.0, 3.0, 4.5, 6.5]) - + ser_ord_int = Series([0, 1, 2, 3]) + ser_ord_float = Series([2.0, 3.0, 4.5, 6.5]) + corr_calc = ser_ord_cat.corr(ser_ord_int, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_int, nan_policy="omit")[0] + corr_expected = method_scipy_func[method]( + ser_ord_cat_codes, ser_ord_int, nan_policy="omit" + )[0] tm.assert_almost_equal(corr_calc, corr_expected) corr_calc = ser_ord_cat.corr(ser_ord_float, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_float, nan_policy="omit")[0] + corr_expected = method_scipy_func[method]( + ser_ord_cat_codes, ser_ord_float, nan_policy="omit" + )[0] tm.assert_almost_equal(corr_calc, corr_expected) corr_calc = ser_ord_cat.corr(ser_ord_cat, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_codes, ser_ord_cat_codes, nan_policy="omit")[0] + corr_expected = method_scipy_func[method]( + ser_ord_cat_codes, ser_ord_cat_codes, nan_policy="omit" + )[0] tm.assert_almost_equal(corr_calc, corr_expected) - ser_ord_cat_shuff = pd.Series( pd.Categorical( - ["high", "low", "very_high", "med"], - categories=["low", "med", "high", "very_high"], ordered=True - )) + ser_ord_cat_shuff = Series( + pd.Categorical( + ["high", "low", "very_high", "med"], + categories=["low", "med", "high", "very_high"], + ordered=True, + ) + ) ser_ord_cat_shuff_codes = ser_ord_cat_shuff.cat.codes.replace(-1, np.nan) - + corr_calc = ser_ord_cat_shuff.corr(ser_ord_cat, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_shuff_codes, ser_ord_cat_codes, nan_policy="omit")[0] + corr_expected = method_scipy_func[method]( + ser_ord_cat_shuff_codes, ser_ord_cat_codes, nan_policy="omit" + )[0] tm.assert_almost_equal(corr_calc, corr_expected) corr_calc = ser_ord_cat_shuff.corr(ser_ord_cat_shuff, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_shuff_codes, ser_ord_cat_shuff_codes, nan_policy="omit")[0] + corr_expected = method_scipy_func[method]( + ser_ord_cat_shuff_codes, ser_ord_cat_shuff_codes, nan_policy="omit" + )[0] tm.assert_almost_equal(corr_calc, corr_expected) - - ser_ord_cat_with_nan = pd.Series( pd.Categorical( - ["h", "low", "vh", None, "m"], - categories=["low", "m", "h", "vh"], ordered=True - )) - ser_ord_cat_shuff_with_nan_codes = ser_ord_cat_with_nan.cat.codes.replace(-1, np.nan) - ser_ord_int = pd.Series([2, 0, 1, 3, None]) + + ser_ord_cat_with_nan = Series( + pd.Categorical( + ["h", "low", "vh", None, "m"], + categories=["low", "m", "h", "vh"], + ordered=True, + ) + ) + ser_ord_cat_shuff_with_nan_codes = ser_ord_cat_with_nan.cat.codes.replace( + -1, np.nan + ) + ser_ord_int = Series([2, 0, 1, 3, None]) corr_calc = ser_ord_cat_with_nan.corr(ser_ord_int, method=method) - corr_expected = method_scipy_func[method](ser_ord_cat_shuff_with_nan_codes, ser_ord_int, nan_policy="omit")[0] - tm.assert_almost_equal(corr_calc, corr_expected) \ No newline at end of file + corr_expected = method_scipy_func[method]( + ser_ord_cat_shuff_with_nan_codes, ser_ord_int, nan_policy="omit" + )[0] + tm.assert_almost_equal(corr_calc, corr_expected) diff --git a/test_corr.py b/test_corr.py index e52674647ef1b..6a06c8821aa05 100644 --- a/test_corr.py +++ b/test_corr.py @@ -1,23 +1,27 @@ import pandas as pd -df = pd.DataFrame({'a' : [1, 2, 3, 4], 'b' : [4, 3, 2, 1]}) -df['b'] = df['b'].astype('category').cat.set_categories([4, 3, 2, 1], ordered=True) -#import pdb; pdb.set_trace() -crr = df.corr(method='spearman') + +df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [4, 3, 2, 1]}) +df["b"] = df["b"].astype("category").cat.set_categories([4, 3, 2, 1], ordered=True) +# import pdb; pdb.set_trace() +crr = df.corr(method="spearman") print(crr) -df = pd.DataFrame({'a' : [1, 2, 3, 4], 'b' : ["vh", "h", "m", "l"]}) -df['b'] = df['b'].astype('category').cat.set_categories(["vh", "h", "m", "l"], ordered=True) -#import pdb; pdb.set_trace() +df = pd.DataFrame({"a": [1, 2, 3, 4], "b": ["vh", "h", "m", "l"]}) +df["b"] = ( + df["b"].astype("category").cat.set_categories(["vh", "h", "m", "l"], ordered=True) +) +# import pdb; pdb.set_trace() print(df) print(df.dtypes) -crr = df.corr(method='spearman') +crr = df.corr(method="spearman") print(crr) -ser_ord_cat = pd.Series( pd.Categorical( - ["vh", "h", "m", "low"], - categories=["vh", "h", "m", "low"], ordered=True - )) +ser_ord_cat = pd.Series( + pd.Categorical( + ["vh", "h", "m", "low"], categories=["vh", "h", "m", "low"], ordered=True + ) +) print(ser_ord_cat) -crr = ser_ord_cat.corr(ser_ord_cat, method='spearman') -print(crr) \ No newline at end of file +crr = ser_ord_cat.corr(ser_ord_cat, method="spearman") +print(crr) From 65a506cc76c9c5f520356718c2915a76bc0e1bc9 Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Mon, 27 Oct 2025 13:42:24 +0000 Subject: [PATCH 6/8] cleanup --- test_corr.py | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 test_corr.py diff --git a/test_corr.py b/test_corr.py deleted file mode 100644 index 6a06c8821aa05..0000000000000 --- a/test_corr.py +++ /dev/null @@ -1,27 +0,0 @@ -import pandas as pd - -df = pd.DataFrame({"a": [1, 2, 3, 4], "b": [4, 3, 2, 1]}) -df["b"] = df["b"].astype("category").cat.set_categories([4, 3, 2, 1], ordered=True) -# import pdb; pdb.set_trace() -crr = df.corr(method="spearman") -print(crr) - - -df = pd.DataFrame({"a": [1, 2, 3, 4], "b": ["vh", "h", "m", "l"]}) -df["b"] = ( - df["b"].astype("category").cat.set_categories(["vh", "h", "m", "l"], ordered=True) -) -# import pdb; pdb.set_trace() -print(df) -print(df.dtypes) -crr = df.corr(method="spearman") -print(crr) - -ser_ord_cat = pd.Series( - pd.Categorical( - ["vh", "h", "m", "low"], categories=["vh", "h", "m", "low"], ordered=True - ) -) -print(ser_ord_cat) -crr = ser_ord_cat.corr(ser_ord_cat, method="spearman") -print(crr) From e93ed835606804990a6041f7c27f862d28de8e4c Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Tue, 4 Nov 2025 20:20:22 +0000 Subject: [PATCH 7/8] test import scipy fix --- pandas/tests/frame/methods/test_cov_corr.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index e56308f48e3c2..41368f8977d4b 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -259,6 +259,7 @@ def test_corr_rank_ordered_categorical( self, method, ): + pytest.importorskip("scipy") df = DataFrame( { "ord_cat": Series( @@ -540,6 +541,7 @@ def test_corr_rank_ordered_categorical( self, method, ): + pytest.importorskip("scipy") df1 = DataFrame( { "a": Series( From ec4d97e299f3678ad7dacc516424625fdbf38cf3 Mon Sep 17 00:00:00 2001 From: Harshit Pande Date: Tue, 4 Nov 2025 21:43:38 +0000 Subject: [PATCH 8/8] rst sorting autofix --- doc/source/whatsnew/v3.0.0.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/source/whatsnew/v3.0.0.rst b/doc/source/whatsnew/v3.0.0.rst index 4722048c8c93e..6f25bcb67df0f 100644 --- a/doc/source/whatsnew/v3.0.0.rst +++ b/doc/source/whatsnew/v3.0.0.rst @@ -210,6 +210,7 @@ Other enhancements - :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now support Python's new-style format strings (e.g., ``"{:.6f}"``) for the ``float_format`` parameter, in addition to old-style ``%`` format strings and callables. This allows for more flexible and modern formatting of floating point numbers when exporting to CSV. (:issue:`49580`) - :meth:`DataFrameGroupBy.transform`, :meth:`SeriesGroupBy.transform`, :meth:`DataFrameGroupBy.agg`, :meth:`SeriesGroupBy.agg`, :meth:`RollingGroupby.apply`, :meth:`ExpandingGroupby.apply`, :meth:`Rolling.apply`, :meth:`Expanding.apply`, :meth:`DataFrame.apply` with ``engine="numba"`` now supports positional arguments passed as kwargs (:issue:`58995`) - :meth:`Rolling.agg`, :meth:`Expanding.agg` and :meth:`ExponentialMovingWindow.agg` now accept :class:`NamedAgg` aggregations through ``**kwargs`` (:issue:`28333`) +- :meth:`Series.corr`, :meth:`DataFrame.corr`, :meth:`DataFrame.corrwith` with ``method="kendall"`` and ``method="spearman"`` now work with ordered categorical data types (:issue:`60306`) - :meth:`Series.map` can now accept kwargs to pass on to func (:issue:`59814`) - :meth:`Series.map` now accepts an ``engine`` parameter to allow execution with a third-party execution engine (:issue:`61125`) - :meth:`Series.rank` and :meth:`DataFrame.rank` with numpy-nullable dtypes preserve ``NA`` values and return ``UInt64`` dtype where appropriate instead of casting ``NA`` to ``NaN`` with ``float64`` dtype (:issue:`62043`)