我有一个具有如下模式的数据集:
df = pl.DataFrame(
{
"target": [
[1.0, 1.0, 0.0],
[1.0, 1.0, 0.1],
[1.0, 1.0, 0.2],
[1.0, 1.0, 0.8],
[1.0, 1.0, 0.9],
[1.0, 1.0, 1.0],
],
"feature": ["a", "b", "c", "d", "e", "f"],
},
schema={
"target": pl.Array(pl.Float32, 3),
"feature": pl.String,
},
)
我想重新采样数据以使其沿 z 方向平坦。
我设法用一种多步骤的黑客方法完成了这件事(而且速度很慢)。我想知道是否有人可以建议一种更干净(和更高效)的方法?
我正在做的是:
- 找到所述直方图的箱边界:
bins = 2 # Use e.g. 100 or larger in reality
z = df.select(z=pl.col("target").arr.get(2))
z_min = z.min()
z_max = z.max()
breaks = np.linspace(z_min, z_max, num=bins+1)
- 找出计数最少的箱子中有多少个计数:
counts = (
df.with_columns(bin=pl.col("target").arr.get(2).cut(breaks))
.with_columns(counter=pl.int_range(pl.len()).over("bin"))
.group_by("bin")
.agg(pl.col("counter").max())
.filter(pl.col("counter") > 0) # <- Nasty way of filtering the (-inf, min] bin
.select(pl.col("counter").min())
).item()
- 在每个箱子上仅选择“计数”元素:
df = (
df.with_columns(bin=pl.col("target").arr.get(2).cut(breaks))
.with_columns(counter=pl.int_range(pl.len()).over("bin"))
.filter(pl.col("counter") <= counts)
.select("target", "feature")
)
大家有什么建议吗?
我认为您无法避免重新采样的这三个步骤(尽管根据您的使用情况,您可以尝试转换数据)
不过你可以稍微优化一下代码,