对具有相同值的行进行聚类而不排序

问题描述 投票:0回答:1

按特定列排序会将这些列下具有相同元组的所有行聚集在一起。我想用相同的值对所有行进行聚类,但保持组的第一个成员出现的顺序相同。

类似这样的:

import polars as pl

df = pl.DataFrame(dict(x=[1,0,1,0], y=[3,1,2,4]))

df.cluster('x')
# shape: (4, 2)
# ┌─────┬─────┐
# │ x   ┆ y   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 1   ┆ 3   │
# │ 1   ┆ 2   │
# │ 0   ┆ 1   │
# │ 0   ┆ 4   │
# └─────┴─────┘
python-polars
1个回答
1
投票

这可以通过以下方式完成:

  1. 临时存储行索引
  2. 将行索引设置为感兴趣列上窗口内的最低值
  3. 按最小索引排序
  4. 删除临时行索引列
import polars as pl

df = pl.DataFrame(dict(x=[1,0,1,0], y=[3,1,2,4]))

(
df
  .with_row_index()
  .with_columns(pl.min('index').over('x'))
  .sort('index')
  .drop('index')
)
# shape: (4, 2)
# ┌─────┬─────┐
# │ x   ┆ y   │
# │ --- ┆ --- │
# │ i64 ┆ i64 │
# ╞═════╪═════╡
# │ 1   ┆ 3   │
# │ 1   ┆ 2   │
# │ 0   ┆ 1   │
# │ 0   ┆ 4   │
# └─────┴─────┘
© www.soinside.com 2019 - 2024. All rights reserved.