如何筛选Pandas DataFrame中typeId为6的行之后的行?
Pandas按typeId筛选目标行
我有如下结构的Pandas DataFrame,需要筛选出typeId列值为6的行之后的行,最终得到两个独立的DataFrame(对应两次出现typeId=6后的目标数据)。
原始DataFrame
| index | typeId |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
| 7 | 1 |
| 8 | 3 |
| 9 | 6 |
| 10 | 1 |
| 11 | 3 |
| 12 | 6 |
| 13 | 1 |
| 14 | 1 |
| 15 | 1 |
| 16 | 1 |
期望结果
第一个DataFrame:
| index | typeId |
|---|---|
| 10 | 1 |
第二个DataFrame:
| index | typeId |
|---|---|
| 13 | 1 |
| 14 | 1 |
| 15 | 1 |
| 16 | 1 |
实现代码
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
相关产品推荐
相关产品推荐

