Ignore leading whitespace when reading csv
Author: Spectre5Created Apr 3, 2025Updated Sep 29, 2026
Labelsenhancement
Description
A white space before or after a number (integer or float) will result in it being interpreted as a string instead of an integer or float. Would it be possible to automatically ignore white space when determining if the column is integer or float? Alternatively, adding a keyword argument to do this?
from io import StringIO
import polars as pl
DATA='1.0, 2.0,3.0 ,4.0\n1.0, 2.0,3.0 ,4.0'
print(pl.read_csv(StringIO(DATA), has_header=False))
DATA='1, 2,3 ,4\n1, 2,3 ,4\n'
print(pl.read_csv(StringIO(DATA), has_header=False))output (column 2 has a leading white space and column 3 a trailing white space):
shape: (2, 4)
┌──────────┬──────────┬──────────┬──────────┐
│ column_1 ┆ column_2 ┆ column_3 ┆ column_4 │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ str ┆ str ┆ f64 │
╞══════════╪══════════╪══════════╪══════════╡
│ 1.0 ┆ 2.0 ┆ 3.0 ┆ 4.0 │
│ 1.0 ┆ 2.0 ┆ 3.0 ┆ 4.0 │
└──────────┴──────────┴──────────┴──────────┘
shape: (2, 4)
┌──────────┬──────────┬──────────┬──────────┐
│ column_1 ┆ column_2 ┆ column_3 ┆ column_4 │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str ┆ i64 │
╞══════════╪══════════╪══════════╪══════════╡
│ 1 ┆ 2 ┆ 3 ┆ 4 │
│ 1 ┆ 2 ┆ 3 ┆ 4 │
└──────────┴──────────┴──────────┴──────────┘Source: pola-rs/polars