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

如何从DataFrame中提取各条件区间内的首个Frame值?

问题描述

现有两个Pandas DataFrame:

  • df 存储帧数据,包含行号、Frame(帧编号)、BodyPart(身体部位)和Likelihood(置信度):
Frame      BodyPart Likelihood
1    907     Nose  0.9538603
2    1240    Mouth  0.9962518
3    200    Mouth  0.9963566
4    1242    Mouth  0.9968582
10   1279    Mouth  0.9953254
11   12000    Mouth  0.9945236
12   14690    Mouth  0.9947007
13   1283    Mouth  0.9932089
14   1291    Mouth  0.9921902
15   17777    Mouth  0.9912276
16   1293    Mouth  0.9907160
17   13100    Mouth  0.9837915
  • condition 记录4个实验条件的起始帧:
condition frame
1        C1     0
2        C2  7796
3        C3 11165
4        C4 14687

需求:从df中提取每个条件区间内的首个Frame值,输出格式如下:

First_C1 First_C2 First_C3 First_C4
1 200      9107      12000    14690
解决方案

使用Pandas的区间筛选和排序功能实现,代码如下:

import pandas as pd

# 为condition添加每个区间的结束帧(下一个条件的起始帧,最后一个区间设为无穷大)
condition['end_frame'] = condition['frame'].shift(-1).fillna(float('inf'))

# 初始化结果字典
first_frames = {}

# 遍历每个条件,筛选对应区间的首个Frame
for _, row in condition.iterrows():
    cond_label = row['condition']
    start = row['frame']
    end = row['end_frame']
    # 筛选区间内的帧并按Frame值排序
    filtered_df = df[(df['Frame'] >= start) & (df['Frame'] < end)].sort_values('Frame')
    # 若有数据则取第一个Frame值
    if not filtered_df.empty:
        first_frames[f'First_{cond_label}'] = filtered_df.iloc[0]['Frame']

# 转换为目标格式的DataFrame
result_df = pd.DataFrame([first_frames])
print(result_df)

说明

  1. 首先给condition添加end_frame列,明确每个条件的帧区间:C1对应[0,7796),C2对应[7796,11165),C3对应[11165,14687),C4对应[14687, ∞)。
  2. 遍历每个条件,筛选df中落在对应区间的行,按Frame升序排序后取第一个值,即为该区间的首个帧。
  3. 最后将结果整理成目标格式的DataFrame。

注:原df中没有落在C2区间[7796,11165)的Frame值,若期望输出中的9107是笔误,可根据实际数据调整区间或补充帧数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:54:53