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

基于Pandas的时序数据过滤:双DataFrame家电用电数据筛选

住宅用电功率监测程序优化需求

现有两个Pandas DataFrame:

  • df_appliances:每10分钟记录各家电功率数据,包含Timestamp、Dishwasher、TV等列
  • df_total:来自另一数据源,记录对应时间点的总用电功率,包含DATETIME、Total_Watts列

需完成两项任务:

  1. 基于df_total中4000瓦的阈值,筛选df_appliances生成新DataFrame df_output
  2. 增加时间过滤规则:记录阈值触发起始时间前20分钟的数据

已实现第一项任务的代码:

start_time = df_total['DATETIME'][df_total['Total_Watts'] >= 4000].tolist()
df_output = df_appliances[df_appliances['Timestamp'].isin(start_time)]

希望获得更优雅的函数式实现方案。


优化实现方案

1. 函数式风格的阈值筛选优化

利用Pandas链式调用+布尔索引,避免冗余中间变量,更贴合函数式编程的简洁性:

df_output = df_appliances[
    df_appliances['Timestamp'].isin(
        df_total.loc[df_total['Total_Watts'] >= 4000, 'DATETIME']
    )
]

如果需要复用逻辑,可以封装成纯函数:

def filter_by_total_threshold(df_appliances, df_total, threshold=4000):
    trigger_times = df_total.loc[df_total['Total_Watts'] >= threshold, 'DATETIME']
    return df_appliances[df_appliances['Timestamp'].isin(trigger_times)]

# 调用示例
df_output = filter_by_total_threshold(df_appliances, df_total)

2. 新增前20分钟数据的时间过滤规则

首先确保时间列是datetime类型(未转换的话先执行转换):

df_appliances['Timestamp'] = pd.to_datetime(df_appliances['Timestamp'])
df_total['DATETIME'] = pd.to_datetime(df_total['DATETIME'])

下面是高效实现时间区间筛选的函数式方案:

def filter_with_pre_trigger_window(df_appliances, df_total, threshold=4000, window_minutes=20):
    # 获取所有触发阈值的时间点
    trigger_times = df_total.loc[df_total['Total_Watts'] >= threshold, 'DATETIME']
    # 生成触发时间对应的前20分钟到触发时间的区间索引
    intervals = pd.IntervalIndex.from_arrays(
        trigger_times - pd.Timedelta(minutes=window_minutes),
        trigger_times,
        closed='both'
    )
    # 筛选落在任意区间内的家电数据
    mask = df_appliances['Timestamp'].apply(lambda ts: ts in intervals)
    return df_appliances[mask]

# 调用示例
df_output = filter_with_pre_trigger_window(df_appliances, df_total)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:01:07