polars.read_csv() 采用德语数字格式
polars.read_csv() with german number formatting
是否有可能在 polars 中读取具有德语数字格式的 csv,就像在 pandas.read_csv() 中使用参数“十进制”和“千”一样
目前,Polars read_csv 方法不公开这些参数。
但是,有一个简单的解决方法来转换它们。例如,使用此 csv,允许 Polars 将 German-formatted 数字读取为 utf8.
from io import StringIO
import polars as pl
my_csv = """col1\tcol2\tcol3
1.234,5\tabc\t1.234.567
9.876\tdef\t3,21
"""
df = pl.read_csv(StringIO(my_csv), sep="\t")
print(df)
shape: (2, 3)
┌─────────┬──────┬───────────┐
│ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════════╪══════╪═══════════╡
│ 1.234,5 ┆ abc ┆ 1.234.567 │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 9.876 ┆ def ┆ 3,21 │
└─────────┴──────┴───────────┘
从这里开始,转换只是几行代码:
df = df.with_column(
pl.col(["col1", "col3"])
.str.replace_all(r"\.", "")
.str.replace(",", ".")
.cast(pl.Float64) # or whatever datatype needed
)
print(df)
shape: (2, 3)
┌────────┬──────┬────────────┐
│ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- │
│ f64 ┆ str ┆ f64 │
╞════════╪══════╪════════════╡
│ 1234.5 ┆ abc ┆ 1.234567e6 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 9876.0 ┆ def ┆ 3.21 │
└────────┴──────┴────────────┘
请注意仅将此逻辑应用于以德语语言环境编码的数字。它会破坏在其他语言环境中格式化的数字。
是否有可能在 polars 中读取具有德语数字格式的 csv,就像在 pandas.read_csv() 中使用参数“十进制”和“千”一样
目前,Polars read_csv 方法不公开这些参数。
但是,有一个简单的解决方法来转换它们。例如,使用此 csv,允许 Polars 将 German-formatted 数字读取为 utf8.
from io import StringIO
import polars as pl
my_csv = """col1\tcol2\tcol3
1.234,5\tabc\t1.234.567
9.876\tdef\t3,21
"""
df = pl.read_csv(StringIO(my_csv), sep="\t")
print(df)
shape: (2, 3)
┌─────────┬──────┬───────────┐
│ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════════╪══════╪═══════════╡
│ 1.234,5 ┆ abc ┆ 1.234.567 │
├╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┤
│ 9.876 ┆ def ┆ 3,21 │
└─────────┴──────┴───────────┘
从这里开始,转换只是几行代码:
df = df.with_column(
pl.col(["col1", "col3"])
.str.replace_all(r"\.", "")
.str.replace(",", ".")
.cast(pl.Float64) # or whatever datatype needed
)
print(df)
shape: (2, 3)
┌────────┬──────┬────────────┐
│ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- │
│ f64 ┆ str ┆ f64 │
╞════════╪══════╪════════════╡
│ 1234.5 ┆ abc ┆ 1.234567e6 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 9876.0 ┆ def ┆ 3.21 │
└────────┴──────┴────────────┘
请注意仅将此逻辑应用于以德语语言环境编码的数字。它会破坏在其他语言环境中格式化的数字。