Polars 0.19版qcut能否返回分位数断点而非数值断点?
在Polars 0.19中让qcut返回分位数断点的实现方法
Polars 0.19版本里,qcut函数默认无法直接返回分位数断点(比如正态分布0.5分位数对应的断点值),当前仅能返回字符串类型的区间标签。虽然可以通过自定义标签转换的方式获取分位数断点,但步骤相对繁琐。
默认qcut返回数值断点的示例
通过include_breaks=True参数可以让qcut返回划分区间的数值断点,但标签仍是区间字符串:
import polars as pl import numpy as np X = pl.DataFrame({"x": np.random.normal(size=100)}) X.select(pl.col("x").qcut([0, 0.5, 1], include_breaks=True).struct.rename_fields(["break", "label"])).unnest("x")
输出:
shape: (100, 2) ┌──────────┬───────────────────────────────────┐ │ break ┆ label │ │ --- ┆ --- │ │ f64 ┆ cat │ ╞══════════╪═══════════════════════════════════╡ │ 2.113793 ┆ (0.07471832756341387, 2.11379302… │ │ 0.074718 ┆ (-2.338473351991288, 0.074718327… │ │ … ┆ … │ └──────────┴───────────────────────────────────┘
自定义标签转换获取分位数断点
通过手动指定分位数值作为标签,再将分类类型的标签转换为数值类型,即可直接得到对应的分位数断点:
y = X.select( pl.col("x") .qcut( [0., 0.5, 1], labels=["0", "0.5", "1", "inf"], include_breaks=True, ) .struct.rename_fields(["break", "label"]) ).unnest("x").with_columns( pl.col("label") .cast(pl.Utf8) # 先将分类类型转为字符串 .cast(pl.Float64) .alias("quantile") )
输出:
shape: (100, 3) ┌───────────┬───────┬──────────┐ │ break ┆ label ┆ quantile │ │ --- ┆ --- ┆ --- │ │ f64 ┆ cat ┆ f64 │ ╞═══════════╪═══════╪══════════╡ │ -0.118428 ┆ 0.5 ┆ 0.5 │ │ 2.90702 ┆ 1 ┆ 1.0 │ │ … ┆ … ┆ … │ └───────────┴───────┴──────────┘
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

