{"record":{"id":"50311348372f0197","repo":"pola-rs/polars","slug":"cannot-convert-dataframe-to-target-mixed-type-c","errorCode":null,"errorMessage":"cannot convert DataFrame to {target} (mixed type columns result in `object` dtype)\\n{df.schema!r}","messagePattern":"cannot convert DataFrame to (.+?) \\(mixed type columns result in `object` dtype\\)\\\\n(.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/ml/utilities.py","lineNumber":29,"sourceCode":"    *,\n    writable: bool,\n    target: str,\n    order: IndexOrder = \"fortran\",\n) -> np.ndarray[Any, Any]:\n    \"\"\"Convert a DataFrame to a NumPy array for use with Jax or PyTorch.\"\"\"\n    for nm, tp in df.schema.items():\n        if tp == List:\n            msg = f\"cannot convert List column {nm!r} to {target} (use Array dtype instead)\"\n            raise TypeError(msg) from None\n\n    if df.width == 1 and df.schema.dtypes()[0] == Array:\n        arr = df[df.columns[0]].to_numpy(writable=writable)\n    else:\n        arr = df.to_numpy(writable=writable, order=order)\n\n    if arr.dtype == object:\n        msg = f\"cannot convert DataFrame to {target} (mixed type columns result in `object` dtype)\\n{df.schema!r}\"\n        raise TypeError(msg)\n    return arr\n","sourceCodeStart":11,"sourceCodeEnd":31,"githubUrl":"https://github.com/pola-rs/polars/blob/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/ml/utilities.py#L11-L31","documentation":"After converting a DataFrame to a numpy array for PyTorch/Jax (frame_to_numpy), if the resulting array has dtype object the values cannot be loaded into a typed tensor, so TypeError is raised with the full frame schema printed for diagnosis. Object dtype appears when the frame mixes incompatible column types (e.g. String alongside numeric) or contains object columns.","triggerScenarios":"df.to_torch() / df.to_jax(return_type='array') where the frame has heterogeneous column dtypes (strings + numbers), pl.Object columns, or unconverted categorical/string features.","commonSituations":"Feeding raw CSV/inferred frames to ML conversion without selecting/casting features; string label columns left in the frame; mixed-type columns from dirty data.","solutions":["Select only numeric feature columns before converting: df.select(cs.numeric()).to_torch()","Cast to a common numeric dtype: df.select(pl.col(c).cast(pl.Float32) for c in cols)","Encode string/categorical columns first (e.g. to codes or one-hot), or exclude them","Read the schema printed in the error to find the offending non-numeric column"],"exampleFix":"# before\ndf.to_torch()  # frame has 'name': String next to numeric columns\n\n# after\nimport polars.selectors as cs\ndf.select(cs.numeric()).cast(pl.Float32).to_torch()","handlingStrategy":"validation","validationCode":"import polars.selectors as cs\nnumeric = df.select(cs.numeric())\nif numeric.width != df.width:\n    bad = [c for c in df.columns if c not in numeric.columns]\n    raise TypeError(f'non-numeric columns block tensor conversion: {bad}')","typeGuard":"import polars as pl\nimport polars.selectors as cs\n\ndef all_numeric(df: pl.DataFrame) -> bool:\n    return df.width == df.select(cs.numeric()).width","tryCatchPattern":null,"preventionTips":["Select and cast features explicitly before to_torch/to_jax; never pass raw inferred frames","Encode labels (strings) to integers before tensor conversion"],"tags":["polars","torch","jax","numpy","dtype","mixed-types"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}