我正在try 使用list[str]
列聚合数据帧中的一些行.对于每个索引,我需要组中所有列表的交集.我不确定我是不是想多了,但我现在不能提供解决方案.有什么需要帮忙的吗?
import polars as pl
input_df = pl.DataFrame(
{"idx": [1,1,2,2,3,3],
"values": [["A", "B"], ["B", "C"], ["A", "B"], ["B", "C"], ["A", "B"], ["B", "C"]]
}
)
output_df = input_df.agg(...)
>>> input_df
shape: (6, 2)
┌─────┬────────────┐
│ idx ┆ values │
│ --- ┆ --- │
│ i64 ┆ list[str] │
╞═════╪════════════╡
│ 1 ┆ ["A", "B"] │
│ 1 ┆ ["B", "C"] │
│ 2 ┆ ["A", "B"] │
│ 2 ┆ ["B", "C"] │
│ 3 ┆ ["A", "B"] │
│ 3 ┆ ["B", "C"] │
└─────┴────────────┘
>>> output_df # Expected output
shape: (3, 2)
┌─────┬───────────┐
│ idx ┆ values │
│ --- ┆ --- │
│ i64 ┆ list[str] │
╞═════╪═══════════╡
│ 1 ┆ ["B"] │
│ 2 ┆ ["B"] │
│ 3 ┆ ["B"] │
└─────┴───────────┘
我试过一些东西,但没有成功
>>> input_df.group_by("idx").agg(
pl.reduce(function=lambda acc, x: acc.list.set_intersection(x),
exprs=pl.col("values"))
)
shape: (3, 2)
┌─────┬──────────────────────────┐
│ idx ┆ values │
│ --- ┆ --- │
│ i64 ┆ list[list[str]] │
╞═════╪══════════════════════════╡
│ 1 ┆ [["A", "B"], ["B", "C"]] │
│ 2 ┆ [["A", "B"], ["B", "C"]] │
│ 3 ┆ [["A", "B"], ["B", "C"]] │
└─────┴──────────────────────────┘
另一个
>>> input_df.group_by("idx").agg(
pl.reduce(function=lambda acc, x: acc.list.set_intersection(x),
exprs=pl.col("values").explode())
)
shape: (3, 2)
┌─────┬───────────────────┐
│ idx ┆ values │
│ --- ┆ --- │
│ i64 ┆ list[str] │
╞═════╪═══════════════════╡
│ 3 ┆ ["A", "B", … "C"] │
│ 2 ┆ ["A", "B", … "C"] │
│ 1 ┆ ["A", "B", … "C"] │
└─────┴───────────────────┘