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

如何使用Pandas识别连续相同值?附数据示例与需求

提取DataFrame中Value为1的连续区间

原始DataFrame

TimestampValue
2021-04-21 14:22:000
2021-04-21 14:23:000
2021-04-21 14:24:000
2021-04-21 14:25:001
2021-04-21 14:26:001
2021-04-21 14:27:000
2021-04-21 14:28:001
2021-04-21 14:29:001
2021-04-21 14:30:001

需求

提取Value为1的连续区间,输出格式如下:

Begin DateAnother headerConsecutive values
2021-04-21 14:25:002021-04-21 14:26:002
2021-04-21 14:28:002021-04-21 14:30:003

解决方案

使用pandas的分组聚合功能可高效实现,步骤如下:

1. 准备数据并转换时间格式

import pandas as pd

# 构造示例数据
data = {
    'Timestamp': ['2021-04-21 14:22:00', '2021-04-21 14:23:00', '2021-04-21 14:24:00',
                  '2021-04-21 14:25:00', '2021-04-21 14:26:00', '2021-04-21 14:27:00',
                  '2021-04-21 14:28:00', '2021-04-21 14:29:00', '2021-04-21 14:30:00'],
    'Value': [0, 0, 0, 1, 1, 0, 1, 1, 1]
}
df = pd.DataFrame(data)
# 转换Timestamp列为datetime类型,确保时间操作正常
df['Timestamp'] = pd.to_datetime(df['Timestamp'])

2. 标记连续值分组

通过对比当前行与前一行的Value,生成分组标识,同一连续区间会被分到同一组:

# 当Value发生变化时,分组编号递增
df['group'] = (df['Value'] != df['Value'].shift()).cumsum()

3. 聚合生成目标结果

过滤出Value为1的行,按分组聚合得到每个连续区间的起始、结束时间和长度:

# 过滤Value=1的组并聚合
result = df[df['Value'] == 1].groupby('group').agg(
    Begin_Date=('Timestamp', 'first'),
    Another_header=('Timestamp', 'last'),
    Consecutive_values=('Timestamp', 'count')
).reset_index(drop=True)

# 重命名列名匹配需求格式
result.columns = ['Begin Date', 'Another header', 'Consecutive values']

4. 输出结果

运行后得到的结果与需求一致:

print(result)

输出:

Begin DateAnother headerConsecutive values
2021-04-21 14:25:002021-04-21 14:26:002
2021-04-21 14:28:002021-04-21 14:30:003

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:15:36