您可以使用DataFrame.with_row_index()
:
import polars as pl
df = pl.DataFrame({"test": np.arange(1, 11)})
print(
df.with_row_index()
.with_columns(
pl.when(pl.col("index") < 5)
.then(None)
.otherwise(pl.col("test"))
.alias("test")
)
.drop("index")
)
打印:
shape: (10, 1)
┌──────┐
│ test │
│ --- │
│ f64 │
╞══════╡
│ Null │
│ Null │
│ Null │
│ Null │
│ Null │
│ 6 │
│ 7 │
│ 8 │
│ 9 │
│ 10 │
└──────┘
或pl.int_range()
,这在团体的情况下提供了更大的灵活性.
print(
(df
.with_columns(
pl.int_range(0, pl.len(), dtype=pl.UInt32).over(True).alias("index")
)
.with_columns(
pl.when(pl.col("index") < 5)
.then(None)
.otherwise(pl.col("test"))
.alias("test")
)
.drop("index")
)
)