分组后我需要对每个组做一些稍微复杂的处理。 在
pandas
中,可以写成如下:
for i,g in df.groupby(['id','sid']):
pass
在极坐标中,
groups
函数返回一个DataFrame,但这不能方便地应用于for循环。
您可以使用分区依据。这将产生一个
dictionary
,其中 group_by
键映射到分区的 DataFrames
。
df = pl.DataFrame({
"groups": [1, 1, 2, 2, 2],
"values": pl.int_range(5, eager=True)
})
part_dfs = df.partition_by("groups", as_dict=True)
print(part_dfs)
{(1,): shape: (2, 2)
┌────────┬────────┐
│ groups ┆ values │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞════════╪════════╡
│ 1 ┆ 0 │
│ 1 ┆ 1 │
└────────┴────────┘,
(2,): shape: (3, 2)
┌────────┬────────┐
│ groups ┆ values │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞════════╪════════╡
│ 2 ┆ 2 │
│ 2 ┆ 3 │
│ 2 ┆ 4 │
└────────┴────────┘}
注意: 结果键以
tuple
形式给出