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

如何提取fear_greed数据集各连续类别组的首条Extreme Fear/Greed记录

提取连续分类区间的首条记录

数据集结构

我的数据集包含以下4列:

  • timestamp:日期字段
  • fear_greed:恐惧贪婪指数数值
  • value_classification:仅包含Extreme Fear和Extreme Greed两类
  • close:价格数据

需求

提取每个连续相同value_classification区间的首条完整记录,即每次类别切换后首次出现的Extreme Fear或Extreme Greed对应的行数据。

输入示例

timestamp  fear_greed value_classification        close
2018-02-02          15         Extreme Fear  8830.750000
2018-02-04          24         Extreme Fear  8277.009766
2018-02-05          11         Extreme Fear  6955.270020
2019-05-11          76        Extreme Greed  7204.771484
2019-05-13          78        Extreme Greed  7814.915039
2019-05-14          78        Extreme Greed  7994.416016
2019-07-15          16         Extreme Fear 10895.089844
2019-07-17          19         Extreme Fear  9693.802734
2019-07-24          20         Extreme Fear  9811.925781
2020-07-28          76        Extreme Greed 10912.823242

期望输出

timestamp  fear_greed value_classification        close
2018-02-02          15         Extreme Fear  8830.750000
2019-05-11          76        Extreme Greed  7204.771484
2019-07-15          16         Extreme Fear 10895.089844
2020-07-28          76        Extreme Greed 10912.823242

解决方案(Python Pandas)

通过生成分组标识区分连续相同分类的区间,再提取每组首条记录:

import pandas as pd

# 确保数据按时间顺序排列(关键前提)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values('timestamp')

# 生成分组ID:当前行分类与上一行不同时,分组ID递增
df['group_id'] = (df['value_classification'] != df['value_classification'].shift()).cumsum()

# 按分组ID提取每组第一条记录,移除临时分组列
result = df.groupby('group_id').first().reset_index(drop=True)

# 输出结果
print(result)

代码说明

  1. 时序校准:先将timestamp转为日期类型并排序,保证数据是按时间顺序处理的,这是判断连续区间的基础。
  2. 分组标记:用shift()获取上一行的分类,与当前行对比,不同则生成新的分组ID,让连续相同分类的行归为同一组。
  3. 提取首条:按分组ID聚合,取每组的第一条数据,即为每个连续分类区间的首条记录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:38:18