我正在尝试搜索是否有一种方法可以轻松更改带数字的字符串的数据类型。比如我面临的问题如下:
df = pl.Dataframe({"foo": ["100CT pen", "pencils 250CT", "what "125CT soever", "this is a thing"]})
我可以提取并创建一个名为 {"bar": ["100", "250", "125", ""]} 的新列。但是后来我找不到一个方便的函数来将此列转换为 Int64 或 float dtypes,以便结果为 [100, 250, 125, null]。
反之亦然。有时使用一个方便的函数将 [100, 250, 125, 0] 列转换为 ["100", "250", "125", "0"] 会很有用。它是已经存在的东西吗?
谢谢!
最佳答案
完成此操作的最简单方法是使用 cast
表达。
将字符串转换为整数(或 float ):
import polars as pl
df = pl.DataFrame({"bar": ["100", "250", "125", ""]})
df.with_column(pl.col('bar').cast(pl.Int64, strict=False).alias('bar_int'))
shape: (4, 2)
┌─────┬─────────┐
│ bar ┆ bar_int │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════════╡
│ 100 ┆ 100 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 250 ┆ 250 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ 125 ┆ 125 │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ ┆ null │
└─────┴─────────┘
一个方便的可用数据类型列表是 here .这些都是 polars
下的别名,因此您可以轻松引用它们(例如,pl.UInt64
)。
对于您描述的数据,我建议使用 strict=False
以避免在数百万条记录中有一个错误的数字导致异常停止一切。
可以使用相同的过程将数字转换为字符串 - 在本例中为 utf8 数据类型。
让我稍微修改一下您的数据集:
df = pl.DataFrame({"bar": [100.5, 250.25, 1250000, None]})
df.with_column(pl.col("bar").cast(pl.Utf8, strict=False).alias("bar_string"))
shape: (4, 2)
┌────────┬────────────┐
│ bar ┆ bar_string │
│ --- ┆ --- │
│ f64 ┆ str │
╞════════╪════════════╡
│ 100.5 ┆ 100.5 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 250.25 ┆ 250.25 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1.25e6 ┆ 1250000.0 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
│ null ┆ null │
└────────┴────────────┘
如果您需要对格式进行更多控制,可以使用 apply
方法和 Python 的新 f 字符串格式。
df.with_column(
pl.col("bar").apply(lambda x: f"This is ${x:,.2f}!").alias("bar_fstring")
)
shape: (4, 2)
┌────────┬────────────────────────┐
│ bar ┆ bar_fstring │
│ --- ┆ --- │
│ f64 ┆ str │
╞════════╪════════════════════════╡
│ 100.5 ┆ This is $100.50! │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 250.25 ┆ This is $250.25! │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 1.25e6 ┆ This is $1,250,000.00! │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ null ┆ null │
└────────┴────────────────────────┘
我找到了 this web page对于那些不熟悉 f 字符串格式的人来说,这是一个方便的引用。
关于python - 极地 : switching between dtypes within a DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71790235/