如何利用pandas DataFrame.rolling()实现特定条件的单元格标记?
Solution Using Pandas Rolling for Row-Wise Window Checks
Got it, let's work through this problem exactly as you asked—using rolling() to mark the last element of 3-consecutive-cell windows where at least 2 values are greater than 10. Here's a step-by-step breakdown with code:
Step 1: Core Logic Overview
We need to:
- First flag which cells have values greater than 10 (convert to a boolean matrix)
- Slide a 3-cell window horizontally across each row
- Check if the window contains 2 or more flagged values
- Mark the last position of qualifying windows as
True, all other positions asFalse
Step 2: Full Code Implementation
import pandas as pd # Your original DataFrame df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[21,22,23,24,25]]) # 1. Create a boolean DataFrame where True = value > 10 gt_10 = df > 10 # 2. Use rolling(window=3) on rows, count True values per window, check if >=2 # Fill NaNs (from incomplete start-of-row windows) with False df1 = gt_10.rolling(window=3, axis=1).sum().ge(2).fillna(False)
Step 3: Verify the Result
If you print df1, you'll get this output that matches your requirements:
0 1 2 3 4 0 False False False False False 1 False False False False False 2 False False True True True 3 False False True True True 4 False False True True True
How It Works
gt_10 = df > 10: Converts your numeric DataFrame into a boolean matrix where each cell isTrueif the value exceeds 10.rolling(window=3, axis=1): Slides a 3-cell window horizontally across each row (axis=1 specifies row-wise operation)..sum(): Counts the number ofTruevalues in each window (sinceTrueis treated as 1 in numeric calculations)..ge(2): Converts the sum result toTrueif the count is 2 or more, otherwiseFalse..fillna(False): The first two positions in each row don't have a full 3-cell window, so they returnNaN—we replace these withFalsebecause they can't meet the condition.
内容的提问来源于stack exchange,提问作者Yi Fang
相关产品推荐
相关产品推荐

