Код: Выделить всё
import polars as pl
df = pl.from_repr("""
┌─────┬─────────┬───────┬───────┐
│ seq ┆ seq_grp ┆ match ┆ score │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 │
╞═════╪═════════╪═══════╪═══════╡
│ foo ┆ aa ┆ aa ┆ 10 │
│ bar ┆ bb ┆ cc ┆ 8 │
│ bar ┆ bb ┆ bb ┆ 20 │
│ duk ┆ dd ┆ dd ┆ 8 │
│ duk ┆ dd ┆ dd ┆ 7 │
│ baz ┆ cc ┆ ff ┆ 5 │
│ baz ┆ cc ┆ cc ┆ 6 │
│ baz ┆ cc ┆ cc ┆ 4 │
│ zed ┆ zz ┆ yy ┆ 6 │
└─────┴─────────┴───────┴───────┘
""")
Код: Выделить всё
grouped_df = (
df.group_by("seq", maintain_order=True)
.all()
.with_columns(pl.col("seq_grp").list.get(0))
)
Код: Выделить всё
┌─────┬─────────┬────────────────────┬───────────┐
│ seq ┆ seq_grp ┆ match ┆ score │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ list[str] ┆ list[i64] │
╞═════╪═════════╪════════════════════╪═══════════╡
│ foo ┆ aa ┆ ["aa"] ┆ [10] │
│ bar ┆ bb ┆ ["cc", "bb"] ┆ [8, 20] │
│ duk ┆ dd ┆ ["dd", "dd"] ┆ [8, 7] │
│ baz ┆ cc ┆ ["ff", "cc", "cc"] ┆ [5, 6, 4] │
│ zed ┆ zz ┆ ["yy"] ┆ [6] │
└─────┴─────────┴────────────────────┴───────────┘
Хотя в этом минимальном примере я мог бы почти добиться этого, используя:
Код: Выделить всё
(df.filter(pl.col("seq_grp") == pl.col("match"))
.group_by("seq").all()
.with_columns(pl.col("score").list.max())
.with_columns(pl.col(["seq_grp", "match"]).list.get(0))
)
Код: Выделить всё
┌─────┬─────────┬───────┬───────┐
│ seq ┆ seq_grp ┆ match ┆ score │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ i64 │
╞═════╪═════════╪═══════╪═══════╡
│ foo ┆ aa ┆ aa ┆ 10 │
| bar ┆ bb ┆ bb ┆ 20 │
│ duk ┆ dd ┆ dd ┆ 8 │
│ baz ┆ cc ┆ cc ┆ 6 │
└─────┴─────────┴───────┴───────┘
Код: Выделить всё
baz ┆ cc ┆ ["ff", "cc", "cc"] ┆ [5, 6, 4] │
│ baz ┆ cc ┆ ["ff", "cc", "cc"] ┆ [5, 6, 4]
Подробнее здесь: https://stackoverflow.com/questions/779 ... her-column
Мобильная версия