听起来你有:
df = pl.read_csv(b"""
name,array,other
a,"1,2,3,4,5,5,5,5",e
b,"1,2,3,4,6,6,6",f
c,"1,2,2,2,2,3,4,6,6,6",g
d,"1,1,1,1,1",h
""").with_columns(
array = pl.format("[{}]", "array").str.json_decode()
).with_row_index()
shape: (4, 4)
┌───────┬──────┬────────────────────────────────┬───────┐
│ index ┆ name ┆ array ┆ other │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ list[i64] ┆ str │
╞═══════╪══════╪════════════════════════════════╪═══════╡
│ 0 ┆ a ┆ [1, 2, 3, 4, 5, 5, 5, 5] ┆ e │
│ 1 ┆ b ┆ [1, 2, 3, 4, 6, 6, 6] ┆ f │
│ 2 ┆ c ┆ [1, 2, 2, 2, 2, 3, 4, 6, 6, 6] ┆ g │
│ 3 ┆ d ┆ [1, 1, 1, 1, 1] ┆ h │
└───────┴──────┴────────────────────────────────┴───────┘
您想要测试array
列中是否存在任何Run-length encoding = N.
Polars有rle
和rle_id
个表情:.rle()
.flatten()
+ .over("index")
是"模拟"基于行的列表操作的一种方法.
df.with_columns(
pl.col("array").flatten().rle().struct["lengths"].max().over("index")
.alias("rle_max_len")
)
shape: (4, 5)
┌───────┬──────┬────────────────────────────────┬───────┬─────────────┐
│ index ┆ name ┆ array ┆ other ┆ rle_max_len │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ list[i64] ┆ str ┆ i32 │
╞═══════╪══════╪════════════════════════════════╪═══════╪═════════════╡
│ 0 ┆ a ┆ [1, 2, 3, 4, 5, 5, 5, 5] ┆ e ┆ 4 │
│ 1 ┆ b ┆ [1, 2, 3, 4, 6, 6, 6] ┆ f ┆ 3 │
│ 2 ┆ c ┆ [1, 2, 2, 2, 2, 3, 4, 6, 6, 6] ┆ g ┆ 4 │
│ 3 ┆ d ┆ [1, 1, 1, 1, 1] ┆ h ┆ 5 │
└───────┴──────┴────────────────────────────────┴───────┴─────────────┘
本质上与做的事情是一样的:
(df.group_by("index")
.agg(
pl.all().first(),
rle_max_len = pl.col("array").flatten().rle().struct["lengths"].max()
)
)
如果您不需要长度,如果需要,可以直接传递到.filter()
.
df.filter(
pl.col("array").flatten().rle().struct["lengths"].max().over("index") > 3
)
shape: (3, 4)
┌───────┬──────┬────────────────────────────────┬───────┐
│ index ┆ name ┆ array ┆ other │
│ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ list[i64] ┆ str │
╞═══════╪══════╪════════════════════════════════╪═══════╡
│ 0 ┆ a ┆ [1, 2, 3, 4, 5, 5, 5, 5] ┆ e │
│ 2 ┆ c ┆ [1, 2, 2, 2, 2, 3, 4, 6, 6, 6] ┆ g │
│ 3 ┆ d ┆ [1, 1, 1, 1, 1] ┆ h │
└───────┴──────┴────────────────────────────────┴───────┘