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

基于24小时周期筛选最低电价时段用于电池充电的技术需求

按每日周期筛选电价最低时段的Pandas实现

需求说明

持有包含日期小时、电价(Price)、碳排放(Carbon)的时间序列数据,需要按每日24小时周期筛选出电价最低的7个时段。当前使用nsmallest(7, columns=['Price'])仅能获取全局范围内的低价时段,无法按日重复执行筛选,需调整代码实现每日自动筛选。

原始数据示例

Price  Carbon
Date and Hour
2024-01-01 00:00:00     20      40
2024-01-01 01:00:00     10      20
2024-01-01 02:00:00     20      40
2024-01-01 03:00:00     30      60
2024-01-01 04:00:00      5      10
2024-01-01 05:00:00      5      10
2024-01-01 06:00:00      5      10
2024-01-01 07:00:00      5      10
2024-01-01 08:00:00      5      10
2024-01-01 09:00:00     30      60
2024-01-01 10:00:00     40      80
2024-01-01 11:00:00     50     100
2024-01-01 12:00:00    100     200
2024-01-01 13:00:00    100     200
2024-01-01 14:00:00    100     200
2024-01-01 15:00:00    100     200
2024-01-01 16:00:00    100     200
2024-01-01 17:00:00    100     200
2024-01-01 18:00:00    100     200
2024-01-01 19:00:00    100     200
2024-01-01 20:00:00    100     200
2024-01-01 21:00:00    100     200

当前代码及问题

当前代码直接全局筛选最低价,无法按日分组:

import pandas as pd
out = df.nsmallest(7, columns=['Price'])
out

当前输出(仅全局前7个低价时段,跨日期但未按日拆分):

Date and Hour  Price  Carbon
4   01/01/2024 04:00      5      10
5   01/01/2024 05:00      5      10
6   01/01/2024 06:00      5      10
7   01/01/2024 07:00      5      10
8   01/01/2024 08:00      5      10
28  02/01/2024 04:00      5      10
29  02/01/2024 05:00      5      10

解决方案:按日期分组筛选

核心思路是用groupby按日期分组,对每个日期的24小时数据单独应用nsmallest筛选。

完整代码

import pandas as pd

# 确保索引为datetime类型(如果原始数据索引不是datetime,先执行此步)
df.index = pd.to_datetime(df.index)

# 按日期分组,每组筛选Price最低的7个时段
daily_low_prices = df.groupby(df.index.date).apply(lambda group: group.nsmallest(7, 'Price'))

# 可选:重置索引,移除分组产生的多级索引,让结果更简洁
daily_low_prices = daily_low_prices.reset_index(level=0, drop=True)

print(daily_low_prices)

代码说明

  1. 索引转换:将Date and Hour索引转为datetime类型,确保能按日期正确分组。
  2. 分组筛选:groupby(df.index.date)按自然日分组,每个分组对应一天的24小时数据;apply(lambda group: group.nsmallest(7, 'Price'))对每组单独筛选最低价的7个时段。
  3. 索引整理:reset_index移除分组产生的额外日期索引层,保持结果结构与原始数据一致。

预期输出示例

针对2024-01-01的数据,会输出当天的7个最低电价时段:

Price  Carbon
Date and Hour
2024-01-01 04:00:00      5      10
2024-01-01 05:00:00      5      10
2024-01-01 06:00:00      5      10
2024-01-01 07:00:00      5      10
2024-01-01 08:00:00      5      10
2024-01-01 01:00:00     10      20
2024-01-01 00:00:00     20      40

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 23:59:53