You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Polars中weight列的值复制value行以构建直方图?

基于Polars按权重列复制行的实现方法

针对你需要根据weight列数值重复对应value行的需求,这里提供两种实用的Polars实现方式:

方法1:向量化操作(推荐,适合大数据集)

利用Polars的repeat和explode函数实现,完全基于向量化运算,性能更优:

import polars as pl

df = pl.DataFrame({"value":[1,2,3], "weight":[2, 2, 1]})

# 生成目标Series
s_result = df.select(pl.col("value").repeat(pl.col("weight"))).explode("value")["value"]

print(s_result)
# 输出结果:
# shape: (5,)
# Series: 'value' [i64]
# [
#   1
#   1
#   2
#   2
#   3
# ]
  • 逻辑说明:pl.col("value").repeat(pl.col("weight"))会将每行的value按对应weight次数重复,生成一个列表类型的列;explode则将列表中的元素逐个展开为独立行,最终提取value列即可得到目标结果。

方法2:Python列表推导式(适合小数据集)

如果数据集规模较小,也可以用Python原生的列表推导式实现:

import polars as pl

df = pl.DataFrame({"value":[1,2,3], "weight":[2, 2, 1]})

# 通过列表推导式生成重复后的数值列表
repeated_values = [v for v, w in zip(df["value"].to_list(), df["weight"].to_list()) for _ in range(w)]
s_result = pl.Series(name="value", values=repeated_values)

print(s_result)

内容的提问来源于stack exchange,提问作者TomNorway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:10:31