我知道 Polars 不支持设计索引,所以
df.filter(expr).index
不是一个选项,我能想到的另一种方法是在应用任何过滤器之前添加一个新列,不确定这是否是这样做的最佳方法极地
df.with_column(pl.Series('index', range(len(df))).filter(expr).index
使用
with_row_count()
:
In [18]: df = pl.DataFrame([pl.Series("a", [5, 9, 6]), pl.Series("b", [8, 3, 4])])
In [19]: df
Out[19]:
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 5 ┆ 8 │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 9 ┆ 3 │
├╌╌╌╌╌┼╌╌╌╌╌┤
│ 6 ┆ 4 │
└─────┴─────┘
In [20]: df.with_row_count()
Out[20]:
shape: (3, 3)
┌────────┬─────┬─────┐
│ row_nr ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞════════╪═════╪═════╡
│ 0 ┆ 5 ┆ 8 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 1 ┆ 9 ┆ 3 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2 ┆ 6 ┆ 4 │
└────────┴─────┴─────┘
# Start from 1 instead of 0.
In [21]: df.with_row_count(offset=1)
Out[21]:
shape: (3, 3)
┌────────┬─────┬─────┐
│ row_nr ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞════════╪═════╪═════╡
│ 1 ┆ 5 ┆ 8 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2 ┆ 9 ┆ 3 │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 3 ┆ 6 ┆ 4 │
└────────┴─────┴─────┘
# Start from 1 and call column "my_index".
In [22]: df.with_row_count(name="my_index", offset=1)
Out[22]:
shape: (3, 3)
┌──────────┬─────┬─────┐
│ my_index ┆ a ┆ b │
│ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 │
╞══════════╪═════╪═════╡
│ 1 ┆ 5 ┆ 8 │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 2 ┆ 9 ┆ 3 │
├╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌╌┤
│ 3 ┆ 6 ┆ 4 │
└──────────┴─────┴─────┘
从新版本的 Polars 开始,
with_row_count()
已被弃用。请改用 with_row_index()
。以下@ghuls 回答:
df.with_row_index(name="my_index", offset=1)