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

如何按日提取DataFrame中4:00-9:30时段low列最低价并生成列表

问题描述

给定如下DataFrame:

timestamp    open    high     low   close   volume
0     2023-01-03 09:30:00  3.5000  3.5800  3.5000  3.5300   1595.0
1     2023-01-03 09:35:00  3.5800  3.5800  3.5800  3.5800    102.0
2     2023-01-03 09:40:00  3.5972  3.5972  3.5972  3.5972    103.0
3     2023-01-03 09:50:00  3.5500  3.5700  3.5000  3.5200   3032.0
4     2023-01-03 09:55:00  3.4100  3.5900  3.4100  3.5900   2205.0
...                   ...     ...     ...     ...     ...      ...
1245  2023-02-21 19:35:00  6.7100  6.7200  6.7100  6.7200    739.0
1246  2023-02-21 19:40:00  6.7200  6.7300  6.7200  6.7300   2243.0
1247  2023-02-21 19:45:00  6.7300  6.7300  6.7000  6.7000   1412.0
1248  2023-02-21 19:50:00  6.7100  6.7400  6.7000  6.7400   4082.0
1249  2023-02-21 19:55:00  6.7400  6.8500  6.6500  6.7200  23678.0

[1250 rows x 6 columns]

需求:按日期提取每天4:00至9:30时段内low列的最低价,将结果存入列表。

用户尝试的代码:

pre_market_low_list = []
for date in olhc.timestamp.dt.date.unique():
    pre_market_low_list.append(pre_market_low(olhc[olhc.timestamp.dt.date == date].low))
解决方案

你的代码存在两个核心问题:未对目标时段做过滤,且pre_market_low函数未定义。以下是两种可行的实现方式:

方法一:修正循环逻辑

import pandas as pd

pre_market_low_list = []
# 确保timestamp为datetime类型
olhc['timestamp'] = pd.to_datetime(olhc['timestamp'])

for date in olhc.timestamp.dt.date.unique():
    # 筛选当天数据
    daily_data = olhc[olhc.timestamp.dt.date == date]
    # 筛选4:00-9:30时段的数据
    time_filter = (daily_data.timestamp.dt.time >= pd.to_datetime('04:00').time()) & \
                  (daily_data.timestamp.dt.time <= pd.to_datetime('09:30').time())
    pre_market_data = daily_data[time_filter]
    # 提取该时段low的最低价,无数据则返回NaN(可按需调整)
    daily_low = pre_market_data['low'].min()
    pre_market_low_list.append(daily_low)

方法二:分组聚合(更高效的Pandas风格)

import pandas as pd

# 确保timestamp为datetime类型
olhc['timestamp'] = pd.to_datetime(olhc['timestamp'])
# 拆分日期和时间列
olhc['date'] = olhc.timestamp.dt.date
olhc['time'] = olhc.timestamp.dt.time

# 筛选目标时段,按日期分组取low的最小值
pre_market_low_series = olhc[
    (olhc['time'] >= pd.to_datetime('04:00').time()) & 
    (olhc['time'] <= pd.to_datetime('09:30').time())
].groupby('date')['low'].min()

# 转换为列表
pre_market_low_list = pre_market_low_series.tolist()

补充说明

  • 若timestamp列原本不是datetime类型,必须先用pd.to_datetime()转换,否则无法提取日期和时间。
  • 若某天4:00-9:30时段无数据,min()会返回NaN,可通过fillna()方法替换为指定值(如0、前一天最低价等),适配业务需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:27:22