python polars将字符串强制转换为数字



应用pandas.to_numeric时,pandas返回的dtype为float64或int64,具体取决于提供的数据。https://pandas.pydata.org/docs/reference/api/pandas.to_numeric.html

在波尔斯语中有这样做的意思吗?

我看到了这个如何用polar将数据类型为List[null]的列强制转换为List[i64],但不想单独强制转换每一列。有几个字符串列,我想变成数字。这可以是int或float值

#code to show casting in pandas.to_numeric
import pandas as pd
df = pd.DataFrame({"col1":["1","2"], "col2":["3.5", "4.6"]})
print("DataFrame:")
print(df)
df[["col1","col2"]]=df[["col1","col2"]].apply(pd.to_numeric)
print(df.dtypes)

与Pandas不同,Polars对数据类型非常挑剔,在自动转换方面往往不太适应。(其中一个原因是性能。(

您可以为to_numeric方法创建一个特性请求(但我不确定响应会有多热情。(

也就是说,这里有一些简单的方法来实现这一点。

创建一个方法

也许最简单的方法是编写一个方法,尝试转换为整数,然后捕获异常。为了方便起见,您甚至可以将此方法附加到Series类本身。

def to_numeric(s: pl.Series) -> pl.Series:
try:
result = s.cast(pl.Int64)
except pl.exceptions.ComputeError:
result = s.cast(pl.Float64)
return result

pl.Series.to_numeric = to_numeric

然后使用它:

(
pl.select(
s.to_numeric()
for s in df
)
)
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ ---  ┆ ---  │
│ i64  ┆ f64  │
╞══════╪══════╡
│ 1    ┆ 3.5  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2    ┆ 4.6  │
└──────┴──────┘

使用csv解析的自动转换

另一种方法是将列写入csv文件(在字符串缓冲区中(,然后让read_csv尝试自动推断类型。在某些情况下,您可能需要调整infer_schema_length参数。

from io import StringIO
pl.read_csv(StringIO(df.write_csv()))
>>> pl.read_csv(StringIO(df.write_csv()))
shape: (2, 2)
┌──────┬──────┐
│ col1 ┆ col2 │
│ ---  ┆ ---  │
│ i64  ┆ f64  │
╞══════╪══════╡
│ 1    ┆ 3.5  │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2    ┆ 4.6  │
└──────┴──────┘

最新更新