chat1
import polars as pl
# Sample DataFrame
df = pl.DataFrame({
"stuff": [None, None, 1, 1, 1, None, None, 1, 1, None, 1, None, 1, 1, 1, 1]
})
# Create a forward-looking column to compare with the current 'stuff' column
df = df.with_column(
pl.col("stuff").shift(-1).alias("next_stuff")
)
# Identify rows where a change from 1 to None or None to 1 will occur
df = df.with_column(
(pl.col("stuff") != pl.col("next_stuff")).alias("will_change")
)
# Count the number of changes from 1 to None, indicating the end of a group of 1s
count_groups = df.filter((pl.col("stuff") == 1) & (pl.col("next_stuff").is_null())).count()
print("Number of contiguous groups of 1s:", count_groups)