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

如何在Pandas DataFrame中保留Blocks相同且Response连续为True的3行

问题:筛选Blocks相同且连续3次Response为True的行

原始DataFrame:

Blocks  Response        RT     Name  
1       7       True            4630   ya__79891       
2       7       True            4610   ya__79891             
3       6       True            4390   ya__79891            
4       6       True            5190   ya__79891            
5       6       True            4260   ya__79891             
6       5       True            3560   ya__79891           
7       5       True            3610   ya__79891 

需求:保留Blocks值相同且Response为True连续出现3次的行,示例中仅保留行3、4、5。

尝试的代码(无法实现需求):

df_1['Points'] = df_1['Response'].astype(int) #converted all the True and False values as 0 and 1
df_1 = df_1[df_1.Points != 0] #remove all the False/0 values

tmp = list(df_1['Blocks']) #created a list of the dataframe colum blocks
tmp = dict(Counter(tmp)) #created a dict`]
wm = [] #empty list for storing Blocks values`
for key,value in tmp.items():
        if(value==3):
            mem = key
            break
    wm.append(mem)
df2 = pd.DataFrame() # new data frame for saving values
df2['Name'] = name
df2['span'] = wm 

简洁实现方法

方法一:基于连续分组筛选

这种方法能准确识别连续相同Blocks的序列,筛选出长度≥3的序列对应的所有行:

import pandas as pd

# 构造示例DataFrame(实际使用时替换为你的数据)
df = pd.DataFrame({
    'Blocks': [7,7,6,6,6,5,5],
    'Response': [True,True,True,True,True,True,True],
    'RT': [4630,4610,4390,5190,4260,3560,3610],
    'Name': ['ya__79891']*7
}, index=[1,2,3,4,5,6,7])

# 1. 先过滤Response不为True的行
df_filtered = df[df['Response'] == True].copy()

# 2. 标记连续相同Blocks的分组:当Blocks与前一行不同时,分组号+1
df_filtered['continuous_group'] = (df_filtered['Blocks'] != df_filtered['Blocks'].shift()).cumsum()

# 3. 统计每个连续分组的行数
group_sizes = df_filtered.groupby('continuous_group')['Blocks'].count()

# 4. 筛选出行数≥3的分组ID
valid_groups = group_sizes[group_sizes >= 3].index

# 5. 提取最终结果
result = df_filtered[df_filtered['continuous_group'].isin(valid_groups)]
print(result)

输出结果:

Blocks  Response    RT       Name  continuous_group
3       6       True      4390  ya__79891  2
4       6       True      5190  ya__79891  2
5       6       True      4260  ya__79891  2

方法二:基于位移判断连续行

如果需要精准匹配连续3次的行序列,可通过位移对比实现:

df_filtered = df[df['Response'] == True].copy()

# 标记连续第三次出现相同Blocks的行
mask = (df_filtered['Blocks'] == df_filtered['Blocks'].shift(1)) & (df_filtered['Blocks'] == df_filtered['Blocks'].shift(2))

# 将标记扩展到前两行,确保连续3行都被保留
final_mask = mask | mask.shift(1).fillna(False) | mask.shift(2).fillna(False)

result = df_filtered[final_mask]

原代码问题说明

原代码核心问题是仅统计Blocks的总出现次数,未考虑「连续」这个关键条件,同时存在语法错误(如name变量未定义、循环缩进错误),因此无法实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:25:31