pola-rs/polars · error · DuplicateError
cannot create a second
Error message
cannot create a second {col!r} column What it means
_xl_inject_dummy_table_columns adds computed/dummy columns to the DataFrame before writing to Excel; if a column definition names a column that already exists in the original df, creating it again would duplicate it, so a DuplicateError is raised.
Solutions
- Rename the definition key to a new column name not present in df.columns
- Remove the duplicate entry from coldefs for columns already in the DataFrame
- If the intent is formatting an existing column, use format/column-width options rather than a column definition
- Ensure the correct DataFrame is being written (schema mismatch between sheets)
Example fix
// before
column_defs = {'total': {'return_dtype': pl.Float64}} # 'total' already in df
// after
column_defs = {'total_calc': {'return_dtype': pl.Float64, 'insert_after': 'total'}} Defensive patterns
Strategy: validation
Validate before calling
dupes = set(coldefs) & set(df.columns)
if dupes:
raise ValueError(f'column definitions collide with existing columns: {dupes}') Try / catch
try:
write_excel(wb, df, column_defs=defs)
except Exception as e:
if "cannot create a second" in str(e):
defs = {k: v for k, v in defs.items() if k not in df.columns}
write_excel(wb, df, column_defs=defs) Prevention
- Keep computed-column names distinct from source df columns
- Diff coldefs keys against df.columns before writing
- Use insert_before/insert_after with new names for derived columns
When it happens
Trigger: write_excel with column_defs (via column_formatting/dummy column specs) where a definition key matches an existing df column name; typically from using a computed-column spec (dict definition) on a column already present in the data.
Common situations: Reusing a column-defs dict across sheets whose DataFrames differ in schema; defining a derived column under a name that already exists instead of a new name.
Understand the failure class
Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.
Related errors
- cannot specify both `columns` and `read_options["columns"]`
- cannot specify both `columns` and…
- cannot specify both `infer_schema_length` and…
- cannot specify both `infer_schema_length` and…
- cannot specify both `sheet_name
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/9cae133237bf9f15.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/io/spreadsheet/_write_utils.py:247
)
def _xl_inject_dummy_table_columns(
df: DataFrame,
coldefs: dict[str, Any],
*,
dtype: dict[str, PolarsDataType] | PolarsDataType | None = None,
expr: Expr | None = None,
) -> DataFrame:
"""Insert dummy frame columns in order to create empty/named table columns."""
df_original_columns = set(df.columns)
df_select_cols = df.columns.copy()
cast_lookup = {}
for col, definition in coldefs.items():
if col in df_original_columns:
msg = f"cannot create a second {col!r} column"
raise DuplicateError(msg)
elif not isinstance(definition, dict):
df_select_cols.append(col)
else:
cast_lookup[col] = definition.get("return_dtype")
insert_before = definition.get("insert_before")
insert_after = definition.get("insert_after")
if insert_after is None and insert_before is None:
df_select_cols.append(col)
else:
insert_idx = (
df_select_cols.index(insert_after) + 1 # type: ignore[arg-type]
if insert_before is None
else df_select_cols.index(insert_before)
)
df_select_cols.insert(insert_idx, col)
expr = F.lit(None) if expr is None else exprView on GitHub (pinned to fe841f959e)