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

如何筛选Pandas DataFrame中typeId为6的行之后的行?

Pandas按typeId筛选目标行

我有如下结构的Pandas DataFrame,需要筛选出typeId列值为6的行之后的行,最终得到两个独立的DataFrame(对应两次出现typeId=6后的目标数据)。

原始DataFrame

indextypeId
12
23
31
41
51
61
71
83
96
101
113
126
131
141
151
161

期望结果

第一个DataFrame:

indextypeId
101

第二个DataFrame:

indextypeId
131
141
151
161

实现代码

import pandas as pd

# 构造原始数据
data = {
    'index': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],
    'typeId': [2,3,1,1,1,1,1,3,6,1,3,6,1,1,1,1]
}
df = pd.DataFrame(data).set_index('index')

# 定位所有typeId为6的行索引
six_positions = df[df['typeId'] == 6].index

# 提取目标数据并拆分
result = []
for pos in six_positions:
    # 取当前6所在行之后的所有行
    after_six = df.loc[pos:].iloc[1:]
    # 筛选连续的typeId=1的行,直到遇到非1值停止
    continuous_ones = after_six[after_six['typeId'] == 1]
    # 找到第一个非1值的位置,截断数据
    first_non_one = after_six[after_six['typeId'] != 1].index.min()
    if first_non_one:
        continuous_ones = continuous_ones.loc[:first_non_one].iloc[:-1]
    result.append(continuous_ones)

# 输出结果
print("第一个DataFrame:\n", result[0])
print("\n第二个DataFrame:\n", result[1])

说明

  • 先定位所有typeId=6的行位置,再分别提取每个位置之后的行
  • 针对每个后续数据集,筛选出连续的typeId=1的记录,直到遇到第一个非1值为止
  • 最终得到两个独立的DataFrame,分别对应两次typeId=6后的目标数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 04:32:50