如何按Pandas DataFrame中标签出现顺序自动提取成对的起止frame值
实现方案
核心逻辑
- 第一步:过滤掉所有
label为other的行,按frame列升序排列保证时间顺序正确 - 第二步:提取过滤后的
frame值为列表,按出现顺序两两配对:第1、3、5……个出现的非other标签作为起始帧,第2、4、6……个作为结束帧
实现代码
import pandas as pd def get_frame_pairs(df): # 过滤目标标签,按frame升序保证顺序正确 target_df = df[df['label'].isin(['hepatic', 'splenic'])].sort_values('frame', ignore_index=True) frame_list = target_df['frame'].tolist() # 按顺序两两分组:步长2取起始帧,步长2从第2位取结束帧 start_frames = frame_list[::2] end_frames = frame_list[1::2] return start_frames, end_frames # 测试用例(已修正df2中hepatic的拼写错误) df1 = pd.DataFrame({'frame':[1,2,3,4,5,6,7,8,9,10,11,12], 'label':['other','splenic','other','other','hepatic','other','other','other','hepatic','other','splenic','other']}) df2 = pd.DataFrame({'frame':[1,2,3,4,5,6,7,8,9,10,11,12], 'label':['other','hepatic','other','other','splenic','other','other','other','splenic','other','hepatic','other']}) print(get_frame_pairs(df1)) # 输出:([2, 9], [5, 11]),和预期完全一致 print(get_frame_pairs(df2)) # 输出:([2, 9], [5, 11])
边界情况说明
如果过滤后的非other标签数量为奇数,最后一个起始帧会没有对应的结束帧,可根据业务需求选择保留该起始帧,或者截取到最近的偶数位数据再配对。
内容的提问来源于stack exchange,提问作者TeoK
相关产品推荐
相关产品推荐

