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

Python Pandas:匹配Channel条件前两行的索引提取问题

Solution

First, let's fix the typo in your original code (you used Chan instead of Channel for the column name—this would cause a KeyError otherwise). Then, to extract the two rows preceding each occurrence of 'A' or 'B' in the Channel column, here's how to do it:

Step 1: Set up your DataFrame and identify target rows

First, let's properly define your sample DataFrame and find the indices of rows where Channel is 'A' or 'B':

import pandas as pd

# Your DataFrame (fixed formatting for clarity)
data = [
    ['Pre', 10, 20, None],
    ['Pre', 35, 42, None],
    ['Event', 'A', 23, 39],
    ['FF', 50, 75, None],
    ['Post', 'A', 79, 11],
    ['Post', 'B', 88, 69]
]
df = pd.DataFrame(data, columns=['Rec', 'Channel', 'Value1', 'Value2'])

# Get indices of rows with Channel 'A' or 'B'
target_indices = df[df['Channel'].isin({'A', 'B'})].index.tolist()

Step 2: Collect preceding rows

Next, we'll gather the two rows before each target index, handling edge cases where a target row is in the first two positions (so fewer than two preceding rows exist):

# Collect indices of all preceding rows we need
needed_indices = []
for idx in target_indices:
    # Add the two rows before the target (if they exist)
    if idx >= 2:
        needed_indices.extend([idx-2, idx-1])
    elif idx == 1:
        needed_indices.append(idx-1)  # Only one row exists before

# Remove duplicate indices (to avoid repeating rows shared between targets)
unique_needed_indices = sorted(list(set(needed_indices)))

# Extract the final result
result_df = df.iloc[unique_needed_indices]

Step 3: View the output

Printing result_df will give you:

Rec Channel  Value1  Value2
0    Pre      10      20     NaN
1    Pre      35      42     NaN
2  Event       A      23    39.0
3     FF      50      75     NaN
4   Post       A      79    11.0

Explanation

  • We first use isin() to locate all rows where Channel matches 'A' or 'B'.
  • For each target row, we add the indices of the two rows before it to our list (adjusting for cases where fewer than two rows exist).
  • We remove duplicate indices to avoid repeating rows that might be shared between multiple target rows (e.g., the row before one target could be the second preceding row for the next target).
  • If you want to keep duplicate rows (e.g., to show the preceding pair for each target separately), skip the unique_needed_indices step and use df.iloc[needed_indices] directly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:15:59