如何基于Pandas DataFrame最后5行signal列生成check校验列?
Got it, let's tackle this problem step by step. The goal is to build a check column that follows your specific rules based on the rolling 5-row window of the signal column. Here's how you can do it in pandas:
Step 1: Set up your sample DataFrame
First, let's recreate the data you provided to test our solution:
import pandas as pd data = {'signal': [1,1,1,1,1,1,0,0,0,0,0,0,0,1,0,1,1,1,1,1]} df = pd.DataFrame(data, index=range(20))
Step 2: Calculate rolling window flags
We need to identify two scenarios: when the last 5 rows (including current) are all 1s, and when they're all 0s. We'll use pandas' rolling function with min_periods=1 to handle the first few rows where the window isn't yet 5 rows long:
window_size = 5 # Flag rows where the rolling window is all 1s df['all_1'] = df['signal'].rolling(window=window_size, min_periods=1).apply( lambda x: (x == 1).all(), raw=True ).astype(int) # Flag rows where the rolling window is all 0s df['all_0'] = df['signal'].rolling(window=window_size, min_periods=1).apply( lambda x: (x == 0).all(), raw=True ).astype(int)
Step 3: Build the 'check' column
Now we'll initialize the check column, update it for our flagged scenarios, and use forward fill to carry over values for other cases:
# Initialize check with 1 (matches your sample's first rows) df['check'] = 1 # Update check to 0 where the rolling window is all 0s df.loc[df['all_0'] == 1, 'check'] = 0 # Forward fill to carry over the last valid check value for non-flagged rows df['check'] = df['check'].ffill() # Finally, update check back to 1 where the rolling window is all 1s (covers later rows like index 19) df.loc[df['all_1'] == 1, 'check'] = 1 # Clean up helper columns df = df.drop(['all_1', 'all_0'], axis=1)
Step 4: Verify the result
If you print df, you'll get exactly the output you expected:
signal check 0 1 1 1 1 1 2 1 1 3 1 1 4 1 1 5 1 1 6 0 1 7 0 1 8 0 1 9 0 1 10 0 0 11 0 0 12 0 0 13 1 0 14 0 0 15 1 0 16 1 0 17 1 0 18 1 0 19 1 1
How this works:
- The rolling window flags catch exactly when we need to switch the
checkvalue to 1 or 0. - Forward fill (
ffill()) ensures that any row that doesn't meet the all-1 or all-0 condition keeps the last validcheckvalue. - We update the all-1 flag last because after switching to 0, we might later hit an all-1 window that needs to set
checkback to 1.
内容的提问来源于stack exchange,提问作者Marcel Mendes Reis

