Here’s one way to solve it using pandas. The key idea is to assign a “measurement number” to each consecutive block of 1s in Column2. Then, if you want, you can split them into separate DataFrames.
import pandas as pd
# Sample DataFrame
data = {
"Column1": [13,12,15,16,15,14,12,11,21,45,44],
"Column2": [1,1,0,0,1,1,1,0,1,1,0]
}
df = pd.DataFrame(data)
# Step 1: Add a new column for measurement numbers
df['Measurement'] = 0
measurement = 0 # Counter for each measurement
in_measurement = False # Flag to track if we are inside a block of 1s
# Step 2: Iterate over rows to assign measurement numbers
for i in range(len(df)):
if df.loc[i, 'Column2'] == 1:
if not in_measurement:
measurement += 1 # Start of a new measurement
in_measurement = True
df.loc[i, 'Measurement'] = measurement
else:
in_measurement = False # End of the current measurement
print(df)
Output:
Column1 Column2 Measurement
0 13 1 1
1 12 1 1
2 15 0 0
3 16 0 0
4 15 1 2
5 14 1 2
6 12 1 2
7 11 0 0
8 21 1 3
9 45 1 3
10 44 0 0
Split into separate DataFrames
Once you have the Measurement column, you can split the DataFrame like this:
# Get unique measurement numbers
measurements = df['Measurement'].unique()
# Create a list of sub-DataFrames
dfs = [df[df['Measurement']==m].drop(columns='Measurement') for m in measurements if m != 0]
# Example: first measurement
df2 = dfs[0]
print(df2)
This will give you:
Column1 Column2
0 13 1
1 12 1
You can similarly access df3, df4, etc.
How this works
in_measurement keeps track of whether you are currently inside a block of 1s.
measurement increments only when a new block starts.
Every 1 in the same block gets the same number.
0s are ignored but mark the end of a block.
After that, splitting into sub-DataFrames is easy.
.diff()and.cumsum().