【发布时间】:2023-02-15 01:42:46
【问题描述】:
是否有可能在 polars 中以德语数字格式读取 csv,就像在 pandas.read_csv() 中使用参数“十进制”和“千”一样
【问题讨论】:
标签: python csv python-polars
是否有可能在 polars 中以德语数字格式读取 csv,就像在 pandas.read_csv() 中使用参数“十进制”和“千”一样
【问题讨论】:
标签: python csv python-polars
目前,Polars read_csv 方法不公开这些参数。
但是,有一个简单的解决方法来转换它们。例如,对于此 csv,允许 Polars 将德语格式的数字读取为 utf8。
from io import StringIO
import polars as pl
my_csv = """col1 col2 col3
1.234,5 abc 1.234.567
9.876 def 3,21
"""
df = pl.read_csv(StringIO(my_csv), sep=" ")
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 │
└────────┴──────┴────────────┘
请注意仅将此逻辑应用于以德语语言环境编码的数字。它会破坏在其他语言环境中格式化的数字。
【讨论】: