From 33a8394aa770172871bdf430258d8e8a4b8cf3e4 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Tue, 3 Nov 2026 22:12:05 -0500 Subject: [PATCH 1/6] Reject ignore_index=True along origin and development in concat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With ignore_index=True, concat renumbered origin or development labels 0, …, n - 1, which drops the grain the labels encode: origins became nanosecond offsets from the Unix epoch (#1489), and development labels were read as months (#1490). Following the discussion in #1489, concat now raises a ValueError for ignore_index=True along either axis. Groupby aggregations still stack one slice per group with ignore_index=True along the grouped axis, which can be origin or development, so they now call a private _concat that holds the existing implementation. Developed with an AI assistant (Árbol, running Muse). --- chainladder/core/pandas.py | 4 +-- chainladder/utils/tests/test_utilities.py | 21 ++++++++------- chainladder/utils/utility_functions.py | 33 ++++++++++++++++++++++- 3 files changed, 46 insertions(+), 12 deletions(-) diff --git a/chainladder/core/pandas.py b/chainladder/core/pandas.py index 2663dec47..c2aafee5d 100644 --- a/chainladder/core/pandas.py +++ b/chainladder/core/pandas.py @@ -1355,7 +1355,7 @@ def add_groupby_agg_func(cls, k: str, v: str): """Aggregate Overrides in GroupBy""" def agg_func(self, *args, **kwargs): - from chainladder.utils import concat + from chainladder.utils.utility_functions import _concat obj = self.obj.copy() auto_sparse = kwargs.pop("auto_sparse", True) @@ -1377,7 +1377,7 @@ def aggregate(i, obj, axis, v): )(self.axis, auto_sparse=False, keepdims=True) for i in self.groups.indices.values() ] - obj = concat(values, axis=self.axis, ignore_index=True) + obj = _concat(values, axis=self.axis, ignore_index=True) group_index = self.groups.first().index if self.axis == 0: if isinstance(group_index, pd.MultiIndex): diff --git a/chainladder/utils/tests/test_utilities.py b/chainladder/utils/tests/test_utilities.py index ae355634e..5b3c97fe1 100644 --- a/chainladder/utils/tests/test_utilities.py +++ b/chainladder/utils/tests/test_utilities.py @@ -613,7 +613,7 @@ def test_concat_axis1_duplicate_columns(raa: Triangle) -> None: def test_concat_ignore_index_axes(raa: Triangle) -> None: - """Test concat with ignore_index=True along axes 0, 1, 2, and 3.""" + """Test concat with ignore_index=True along axes 0 and 1.""" res0 = cl.concat([raa, raa], axis=0, ignore_index=True) assert len(res0.index) == 2 assert res0.key_labels == ["Index"] @@ -624,15 +624,18 @@ def test_concat_ignore_index_axes(raa: Triangle) -> None: res1 = cl.concat([t1, t2], axis=1, ignore_index=True) assert list(res1.columns) == [0, 1] - o1 = raa.iloc[:, :, :5, :] - o2 = raa.iloc[:, :, 5:, :] - res2 = cl.concat([o1, o2], axis=2, ignore_index=True) - assert len(res2.odims) == len(raa.odims) - d1 = raa.iloc[:, :, :, :5] - d2 = raa.iloc[:, :, :, 5:] - res3 = cl.concat([d1, d2], axis=3, ignore_index=True) - assert len(res3.ddims) == len(raa.ddims) +@pytest.mark.parametrize("axis", [2, 3, "origin", "development", -2, -1]) +def test_concat_ignore_index_origin_development_raises( + raa: Triangle, axis: int | str +) -> None: + """Concat rejects ignore_index=True along origin and development (#1489, #1490).""" + if raa._get_axis(axis) == 2: + pieces = [raa.iloc[:, :, :5, :], raa.iloc[:, :, 5:, :]] + else: + pieces = [raa.iloc[:, :, :, :5], raa.iloc[:, :, :, 5:]] + with pytest.raises(ValueError, match="ignore_index=True is not supported"): + cl.concat(pieces, axis=axis, ignore_index=True) def test_concat_axis_1_index_dtype_relaxed(raa: Triangle) -> None: diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index 22fc3340e..1d8582b94 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -620,7 +620,9 @@ def concat( resulting axis will be labeled 0, …, n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other - axes are still respected in the join. + axes are still respected in the join. Only the index and columns axes + accept ``ignore_index=True``: origin and development labels carry the + triangle's grain, so they cannot be renumbered. sort: bool If True, sort the result along the desired axis. @@ -628,6 +630,14 @@ def concat( ------- Updated triangle + Raises + ------ + TypeError + If ``objs`` is not a list or tuple. + ValueError + If ``objs`` is empty, or if ``ignore_index=True`` is passed with the + origin or development axis. + Examples -------- When paid and incurred triangles are constructed separately, ``concat`` @@ -687,6 +697,27 @@ def concat( objs = list(objs) if len(objs) == 0: raise ValueError("objs must contain at least one element") + if ignore_index and objs[0]._get_axis(axis) in (2, 3): + raise ValueError( + "ignore_index=True is not supported along the origin or development " + "axis, because their labels carry the triangle's grain." + ) + return _concat(objs, axis, ignore_index=ignore_index, sort=sort) + + +def _concat( + objs: list, + axis: Union[int, str], + ignore_index: bool = False, + sort: bool = False, +): + """ + Concatenate Triangle objects, allowing ``ignore_index=True`` on any axis. + + Groupby aggregations stack one slice per group with ``ignore_index=True`` + along the grouped axis, which can be origin or development. ``concat`` + rejects that combination, so they call this instead. + """ xp = objs[0].get_array_module() axis = objs[0]._get_axis(axis) From 5fd1f18b6090fe95ceaf9f2556adc6bd70696a80 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Tue, 3 Nov 2026 22:14:04 -0500 Subject: [PATCH 2/6] Raise descriptive ValueErrors from concat's label checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit concat checked its inputs with bare asserts, so a failed check surfaced as an AssertionError with no message (#1489), and under python -O the checks did not run at all. Each check now raises a ValueError that says what went wrong: - a label repeats along the concatenation axis. The message names the repeated labels, and for origin periods it points to adding the triangles with +, the route discussed in #1489. - the index, origin periods or development periods differ along an axis other than the concatenation axis. Differing lengths get this message too, where numpy raised an "inhomogeneous shape" error before. Repeated labels are reported first, so splitting a triangle at an origin period and concatenating the pieces, the case in #1489, gets the hint about + even when the pieces' development periods also differ. Every input that failed a check before still fails, now with a ValueError. Developed with an AI assistant (Árbol, running Muse). --- chainladder/utils/tests/test_utilities.py | 44 +++++++++++- chainladder/utils/utility_functions.py | 85 +++++++++++++++++++---- 2 files changed, 113 insertions(+), 16 deletions(-) diff --git a/chainladder/utils/tests/test_utilities.py b/chainladder/utils/tests/test_utilities.py index 5b3c97fe1..9d440f0f1 100644 --- a/chainladder/utils/tests/test_utilities.py +++ b/chainladder/utils/tests/test_utilities.py @@ -595,7 +595,7 @@ def test_concat_axis1(raa: Triangle) -> None: def test_concat_axis1_duplicate_columns(raa: Triangle) -> None: """ - Concat two triangles along the column axis with the same column names. Raise an assertion error since + Concat two triangles along the column axis with the same column names. Raise a ValueError since columns must be unique. Parameters @@ -608,10 +608,50 @@ def test_concat_axis1_duplicate_columns(raa: Triangle) -> None: None """ - with pytest.raises(AssertionError): + with pytest.raises(ValueError, match="Column labels repeat"): cl.concat([raa, raa], axis=1) +@pytest.mark.parametrize( + "axis, message", + [ + (0, r"Index labels repeat across the triangles: \[\{'Total': 'Total'\}\]"), + (2, r"Origin periods repeat across the triangles: \['1986-01-01'\]"), + (3, r"Development periods repeat across the triangles: \[72\]"), + ], +) +def test_concat_repeated_labels_raise(raa: Triangle, axis: int, message: str) -> None: + """Concat names the labels that repeat along the concatenation axis.""" + if axis == 0: + pieces = [raa, raa] + elif axis == 2: + pieces = [raa.iloc[:, :, :6, :], raa.iloc[:, :, 5:, :]] + else: + pieces = [raa.iloc[:, :, :, :6], raa.iloc[:, :, :, 5:]] + with pytest.raises(ValueError, match=message): + cl.concat(pieces, axis=axis) + + +def test_concat_reports_repeated_origins_first(raa: Triangle) -> None: + """Repeated origins are reported before a development mismatch (#1489).""" + older = raa.iloc[:, :, :6, :] + newer = raa.iloc[:, :, 5:, :5] + with pytest.raises(ValueError, match=r"Origin periods repeat.*triangles with \+"): + cl.concat([older, newer], axis=2) + + +def test_concat_misaligned_axes_raise(clrd: Triangle) -> None: + """Concat explains which axis differs when the non-concatenation axes disagree.""" + tri = clrd.groupby("LOB").sum()["CumPaidLoss"] + wkcomp, comauto = tri.loc["wkcomp"], tri.loc["comauto"] + with pytest.raises(ValueError, match="same index"): + cl.concat([wkcomp, comauto.rename("columns", ["Other"])], axis=1) + with pytest.raises(ValueError, match="same origin periods"): + cl.concat([wkcomp, comauto.iloc[:, :, 1:, :]], axis=0) + with pytest.raises(ValueError, match="same development periods"): + cl.concat([wkcomp, comauto.iloc[:, :, :, 1:]], axis=0) + + def test_concat_ignore_index_axes(raa: Triangle) -> None: """Test concat with ignore_index=True along axes 0 and 1.""" res0 = cl.concat([raa, raa], axis=0, ignore_index=True) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index 1d8582b94..9e8b831de 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -599,6 +599,56 @@ def set_common_backend(objs): return [i.set_backend(backend) for i in objs] +def _labels_match(labels: list) -> bool: + """Return whether every array of axis labels in ``labels`` equals the first.""" + first = labels[0] + return all( + len(other) == len(first) and bool(np.all(other == first)) + for other in labels[1:] + ) + + +def _repeated(labels) -> list: + """Return each label that occurs more than once in ``labels``, once.""" + labels = pd.Index(labels) + repeated = labels[labels.duplicated()].unique() + if isinstance(repeated, pd.DatetimeIndex): + return repeated.strftime("%Y-%m-%d").tolist() + return repeated.tolist() + + +def _check_unique_labels(objs: list, axis: int) -> None: + """Raise a ValueError naming any label that repeats along ``axis``.""" + if axis == 0: + index = pd.concat([obj.index for obj in objs], ignore_index=True) + if len(index.drop_duplicates()) != len(index): + repeated = index[index.duplicated()].drop_duplicates() + raise ValueError( + "Index labels repeat across the triangles: " + f"{repeated.to_dict('records')}. Pass ignore_index=True to " + "number the index 0, …, n - 1." + ) + return + attribute = {1: "columns", 2: "odims", 3: "ddims"}[axis] + labels = np.concatenate([getattr(obj, attribute) for obj in objs]) + if len(labels) == len(set(labels)): + return + if axis == 1: + raise ValueError( + f"Column labels repeat across the triangles: {_repeated(labels)}. " + "Rename the columns or pass ignore_index=True." + ) + if axis == 2: + raise ValueError( + f"Origin periods repeat across the triangles: {_repeated(labels)}. " + "To combine amounts for the same origin periods, add the triangles " + "with + instead." + ) + raise ValueError( + f"Development periods repeat across the triangles: {_repeated(labels)}." + ) + + def concat( objs: list | tuple, axis: Union[int, str], @@ -635,8 +685,9 @@ def concat( TypeError If ``objs`` is not a list or tuple. ValueError - If ``objs`` is empty, or if ``ignore_index=True`` is passed with the - origin or development axis. + If ``objs`` is empty, if ``ignore_index=True`` is passed with the + origin or development axis, if the triangles differ along an axis other + than ``axis``, or if a label repeats along ``axis``. Examples -------- @@ -737,9 +788,11 @@ def _concat( if list(objs[num].columns) != all_columns: objs[num] = objs[num][all_columns] objs = set_common_backend(objs) + if not ignore_index: + _check_unique_labels(objs, axis) if axis != 0: for obj in objs[1:]: - assert ( + if not ( list(obj.index.columns) == list(objs[0].index.columns) and obj.index.shape == objs[0].index.shape and bool( @@ -748,13 +801,21 @@ def _concat( | (pd.isna(obj.index.values) & pd.isna(objs[0].index.values)) ).all() ) - ) - if axis != 2: - a = np.array([obj.odims for obj in objs]) - assert np.all(a == a[0]) - if axis != 3: - a = np.array([obj.ddims for obj in objs]) - assert np.all(a == a[0]) + ): + raise ValueError( + "All triangles must have the same index to be concatenated " + "along columns, origin or development." + ) + if axis != 2 and not _labels_match([obj.odims for obj in objs]): + raise ValueError( + "All triangles must have the same origin periods to be concatenated " + "along index, columns or development." + ) + if axis != 3 and not _labels_match([obj.ddims for obj in objs]): + raise ValueError( + "All triangles must have the same development periods to be " + "concatenated along index, columns or origin." + ) out = copy.deepcopy(objs[0]) out.values = xp.concatenate([obj.values for obj in objs], axis=axis) @@ -766,7 +827,6 @@ def _concat( out.key_labels = ["Index"] else: new_axis = pd.concat([obj.index for obj in objs], ignore_index=True) - assert len(new_axis.drop_duplicates()) == len(new_axis) out.index = new_axis out.key_labels = list(new_axis.columns) elif axis == 1: @@ -778,21 +838,18 @@ def _concat( new_axis = pd.Index( np.concatenate([obj.columns for obj in objs]), name="columns" ) - assert len(new_axis) == len(set(new_axis)) out.columns = new_axis elif axis == 2: if ignore_index: new_axis = np.arange(sum([len(obj.odims) for obj in objs])) else: new_axis = np.concatenate([obj.odims for obj in objs]) - assert len(new_axis) == len(set(new_axis)) out.odims = new_axis elif axis == 3: if ignore_index: new_axis = np.arange(sum([len(obj.ddims) for obj in objs])) else: new_axis = np.concatenate([obj.ddims for obj in objs]) - assert len(new_axis) == len(set(new_axis)) out.ddims = new_axis if out.ddims.dtype == __dt64_dtype__ and type(out.ddims) is np.ndarray: out.ddims = pd.DatetimeIndex(out.ddims) From 226f24ae35bcf6697cec03a86af76e2b5cab3bb7 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Tue, 3 Nov 2026 22:37:56 -0500 Subject: [PATCH 3/6] Sort imports in utility_functions.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apply the import order that the Ruff workflow's "Suggest import sorting for changed files" step proposes for utility_functions.py (ruff 0.16.1 check --select I --fix). Only import lines move. The step checks whole files, so this also sorts imports that were already on main. core/pandas.py and test_utilities.py are left as they are: #1304 edits the import block of core/pandas.py, and #1465 removes an import and several tests from test_utilities.py, so sorting either file here would conflict with those PRs. Developed with an AI assistant (Árbol, running Muse). --- chainladder/utils/utility_functions.py | 31 +++++++++++++++----------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index 9e8b831de..6c9b22bc8 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -4,33 +4,38 @@ from __future__ import annotations import copy -import dill import json import os import warnings + +from io import StringIO +from typing import TYPE_CHECKING, Optional, Union + +import dill import numpy as np import pandas as pd -from chainladder import __dt64_unit__, __dt64_dtype__ -from chainladder._config.deprecation import _deprecated_rename -from chainladder.utils.sparse import sp -from chainladder.utils.data._manifest import SAMPLES -from chainladder._config.deprecation import _deprecated_rename_argument - -from io import StringIO from patsy import dmatrix # noqa from sklearn.base import BaseEstimator, TransformerMixin -from typing import Union, Optional, TYPE_CHECKING +from chainladder import __dt64_dtype__, __dt64_unit__ +from chainladder._config.deprecation import ( + _deprecated_rename, + _deprecated_rename_argument, +) +from chainladder.utils.data._manifest import SAMPLES +from chainladder.utils.sparse import sp if TYPE_CHECKING: - from chainladder import Triangle, MethodBase, Pipeline - from numpy.typing import ArrayLike - from pandas import DataFrame - from sparse import COO from types import ModuleType from typing import AnyStr + + from numpy.typing import ArrayLike + from pandas import DataFrame from pandas._typing import FilePath, ReadCsvBuffer + from sparse import COO + + from chainladder import MethodBase, Pipeline, Triangle def load_sample(key: str, *args, **kwargs) -> Triangle: From 37755508d76200ddacae4da447d5b93bf565dd02 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Wed, 4 Nov 2026 21:25:49 -0500 Subject: [PATCH 4/6] Use the public concat in groupby aggregation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the private _concat, as suggested in review. The groupby aggregation helper now calls concat with ignore_index=True only when it groups the index or columns: aggregating relabels those slices "(All)" or 0, and the helper sets the real labels afterwards. Origin and development slices are concatenated with their own labels. grain() is unaffected. It groups a valuation triangle, where each summed slice keeps its first origin or its own valuation date, so the labels are distinct. Calling groupby(..., axis=3) directly on a development triangle now raises, because summing a development slice labels it with the triangle's valuation date and every group gets the same label; on main that call returns development labels 0, ..., n - 1. Developed with an AI assistant (Árbol, running Muse). --- chainladder/core/pandas.py | 6 ++++-- chainladder/utils/utility_functions.py | 16 ---------------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/chainladder/core/pandas.py b/chainladder/core/pandas.py index c2aafee5d..ed3fdb6f6 100644 --- a/chainladder/core/pandas.py +++ b/chainladder/core/pandas.py @@ -1355,7 +1355,7 @@ def add_groupby_agg_func(cls, k: str, v: str): """Aggregate Overrides in GroupBy""" def agg_func(self, *args, **kwargs): - from chainladder.utils.utility_functions import _concat + from chainladder.utils import concat obj = self.obj.copy() auto_sparse = kwargs.pop("auto_sparse", True) @@ -1377,7 +1377,9 @@ def aggregate(i, obj, axis, v): )(self.axis, auto_sparse=False, keepdims=True) for i in self.groups.indices.values() ] - obj = _concat(values, axis=self.axis, ignore_index=True) + # Aggregated index and column slices share placeholder labels, which are + # replaced below, so only those axes are concatenated with ignore_index. + obj = concat(values, axis=self.axis, ignore_index=self.axis in (0, 1)) group_index = self.groups.first().index if self.axis == 0: if isinstance(group_index, pd.MultiIndex): diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index 6c9b22bc8..e1d43c3ce 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -758,22 +758,6 @@ def concat( "ignore_index=True is not supported along the origin or development " "axis, because their labels carry the triangle's grain." ) - return _concat(objs, axis, ignore_index=ignore_index, sort=sort) - - -def _concat( - objs: list, - axis: Union[int, str], - ignore_index: bool = False, - sort: bool = False, -): - """ - Concatenate Triangle objects, allowing ``ignore_index=True`` on any axis. - - Groupby aggregations stack one slice per group with ``ignore_index=True`` - along the grouped axis, which can be origin or development. ``concat`` - rejects that combination, so they call this instead. - """ xp = objs[0].get_array_module() axis = objs[0]._get_axis(axis) From 3e65a2f0ab86f0876de01f7c5bcd133d0576dd54 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Wed, 4 Nov 2026 21:25:49 -0500 Subject: [PATCH 5/6] Define concat's label helpers inside concat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three label helpers are used only by concat, so they move into it, as suggested in review. _repeated becomes repeated_labels, because check_unique_labels already uses repeated as a local name. Developed with an AI assistant (Árbol, running Muse). --- chainladder/utils/utility_functions.py | 106 ++++++++++++------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index e1d43c3ce..681c5bf9d 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -604,56 +604,6 @@ def set_common_backend(objs): return [i.set_backend(backend) for i in objs] -def _labels_match(labels: list) -> bool: - """Return whether every array of axis labels in ``labels`` equals the first.""" - first = labels[0] - return all( - len(other) == len(first) and bool(np.all(other == first)) - for other in labels[1:] - ) - - -def _repeated(labels) -> list: - """Return each label that occurs more than once in ``labels``, once.""" - labels = pd.Index(labels) - repeated = labels[labels.duplicated()].unique() - if isinstance(repeated, pd.DatetimeIndex): - return repeated.strftime("%Y-%m-%d").tolist() - return repeated.tolist() - - -def _check_unique_labels(objs: list, axis: int) -> None: - """Raise a ValueError naming any label that repeats along ``axis``.""" - if axis == 0: - index = pd.concat([obj.index for obj in objs], ignore_index=True) - if len(index.drop_duplicates()) != len(index): - repeated = index[index.duplicated()].drop_duplicates() - raise ValueError( - "Index labels repeat across the triangles: " - f"{repeated.to_dict('records')}. Pass ignore_index=True to " - "number the index 0, …, n - 1." - ) - return - attribute = {1: "columns", 2: "odims", 3: "ddims"}[axis] - labels = np.concatenate([getattr(obj, attribute) for obj in objs]) - if len(labels) == len(set(labels)): - return - if axis == 1: - raise ValueError( - f"Column labels repeat across the triangles: {_repeated(labels)}. " - "Rename the columns or pass ignore_index=True." - ) - if axis == 2: - raise ValueError( - f"Origin periods repeat across the triangles: {_repeated(labels)}. " - "To combine amounts for the same origin periods, add the triangles " - "with + instead." - ) - raise ValueError( - f"Development periods repeat across the triangles: {_repeated(labels)}." - ) - - def concat( objs: list | tuple, axis: Union[int, str], @@ -747,6 +697,56 @@ def concat( 1996 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1997 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN """ + + def labels_match(labels: list) -> bool: + """Return whether every array of axis labels in ``labels`` equals the first.""" + first = labels[0] + return all( + len(other) == len(first) and bool(np.all(other == first)) + for other in labels[1:] + ) + + def repeated_labels(labels) -> list: + """Return each label that occurs more than once in ``labels``, once.""" + labels = pd.Index(labels) + repeated = labels[labels.duplicated()].unique() + if isinstance(repeated, pd.DatetimeIndex): + return repeated.strftime("%Y-%m-%d").tolist() + return repeated.tolist() + + def check_unique_labels(objs: list, axis: int) -> None: + """Raise a ValueError naming any label that repeats along ``axis``.""" + if axis == 0: + index = pd.concat([obj.index for obj in objs], ignore_index=True) + if len(index.drop_duplicates()) != len(index): + repeated = index[index.duplicated()].drop_duplicates() + raise ValueError( + "Index labels repeat across the triangles: " + f"{repeated.to_dict('records')}. Pass ignore_index=True to " + "number the index 0, …, n - 1." + ) + return + attribute = {1: "columns", 2: "odims", 3: "ddims"}[axis] + labels = np.concatenate([getattr(obj, attribute) for obj in objs]) + if len(labels) == len(set(labels)): + return + if axis == 1: + raise ValueError( + "Column labels repeat across the triangles: " + f"{repeated_labels(labels)}. Rename the columns or pass " + "ignore_index=True." + ) + if axis == 2: + raise ValueError( + "Origin periods repeat across the triangles: " + f"{repeated_labels(labels)}. To combine amounts for the same " + "origin periods, add the triangles with + instead." + ) + raise ValueError( + "Development periods repeat across the triangles: " + f"{repeated_labels(labels)}." + ) + if type(objs) not in (list, tuple): raise TypeError("objects to be concatenated must be in a list or tuple") if type(objs) is tuple: @@ -778,7 +778,7 @@ def concat( objs[num] = objs[num][all_columns] objs = set_common_backend(objs) if not ignore_index: - _check_unique_labels(objs, axis) + check_unique_labels(objs, axis) if axis != 0: for obj in objs[1:]: if not ( @@ -795,12 +795,12 @@ def concat( "All triangles must have the same index to be concatenated " "along columns, origin or development." ) - if axis != 2 and not _labels_match([obj.odims for obj in objs]): + if axis != 2 and not labels_match([obj.odims for obj in objs]): raise ValueError( "All triangles must have the same origin periods to be concatenated " "along index, columns or development." ) - if axis != 3 and not _labels_match([obj.ddims for obj in objs]): + if axis != 3 and not labels_match([obj.ddims for obj in objs]): raise ValueError( "All triangles must have the same development periods to be " "concatenated along index, columns or origin." From 8ecd1fd2ae9ad7167230f817671efbea7c482593 Mon Sep 17 00:00:00 2001 From: Simon Koch-Sultan Date: Wed, 4 Nov 2026 22:20:04 -0500 Subject: [PATCH 6/6] Drop concat's unreachable ignore_index branches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit concat raises for ignore_index=True along origin or development before it builds the new axis, so the branches that numbered origin and development labels 0, ..., n - 1 can no longer run. Remove them. Developed with an AI assistant (Árbol, running Muse). --- chainladder/utils/utility_functions.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index 681c5bf9d..18e55679c 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -829,17 +829,9 @@ def check_unique_labels(objs: list, axis: int) -> None: ) out.columns = new_axis elif axis == 2: - if ignore_index: - new_axis = np.arange(sum([len(obj.odims) for obj in objs])) - else: - new_axis = np.concatenate([obj.odims for obj in objs]) - out.odims = new_axis + out.odims = np.concatenate([obj.odims for obj in objs]) elif axis == 3: - if ignore_index: - new_axis = np.arange(sum([len(obj.ddims) for obj in objs])) - else: - new_axis = np.concatenate([obj.ddims for obj in objs]) - out.ddims = new_axis + out.ddims = np.concatenate([obj.ddims for obj in objs]) if out.ddims.dtype == __dt64_dtype__ and type(out.ddims) is np.ndarray: out.ddims = pd.DatetimeIndex(out.ddims)