Skip to content

Commit cd781db

Browse files
authored
feat: better error message for duplicate column names in pandas (#1270)
1 parent 4c77fa5 commit cd781db

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

narwhals/_pandas_like/dataframe.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,14 @@ def _validate_columns(self, columns: pd.Index) -> None:
8989
raise ValueError(msg) from None
9090

9191
if len(columns) != len_unique_columns:
92-
msg = f"Expected unique column names, got: {columns}"
92+
from collections import Counter
93+
94+
counter = Counter(columns)
95+
msg = ""
96+
for key, value in counter.items():
97+
if value > 1:
98+
msg += f"\n- '{key}' {value} times"
99+
msg = f"Expected unique column names, got:{msg}"
93100
raise ValueError(msg)
94101

95102
def _from_native_frame(self, df: Any) -> Self:

tests/translate/from_native_test.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,9 @@ def test_pandas_like_validate() -> None:
151151
df2 = pd.DataFrame({"b": [1, 2, 3]})
152152
df = pd.concat([df1, df2, df2], axis=1)
153153

154-
with pytest.raises(ValueError, match="Expected unique column names"):
154+
with pytest.raises(
155+
ValueError, match=r"Expected unique column names, got:\n- 'b' 2 times"
156+
):
155157
nw.from_native(df)
156158

157159

0 commit comments

Comments
 (0)