You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用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 as False

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 is True if 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 of True values in each window (since True is treated as 1 in numeric calculations).
  • .ge(2): Converts the sum result to True if the count is 2 or more, otherwise False.
  • .fillna(False): The first two positions in each row don't have a full 3-cell window, so they return NaN—we replace these with False because they can't meet the condition.

内容的提问来源于stack exchange,提问作者Yi Fang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:53:49