如何用pandas时间序列Output_Energy列逐分钟递增常量至目标值
解决方案
方案1:pandas向量化实现(推荐,执行效率更高)
import pandas as pd # 初始值设置 init_val = 30 target_val = 80 need_total = target_val - init_val # 计算Output_Energy累计和 df["cumulative_energy"] = df["Output_Energy"].cumsum() # 定位首次达到阈值的位置 reach_mask = df["cumulative_energy"] >= need_total if reach_mask.any(): stop_timestamp = reach_mask.idxmax() final_result = init_val + df.loc[stop_timestamp, "cumulative_energy"] print(f"累计至{stop_timestamp}时达到阈值,最终数值为{final_result:.2f}") # 如需获取截止到该时刻的所有数据,可调用下方代码 valid_df = df.loc[:stop_timestamp, :].copy() else: print("现有2天数据的Output_Energy总和不足,无法让初始值累加到80")
方案2:while循环实现(匹配你最初的实现思路)
init_val = 30 target_val = 80 current = init_val row_num = 0 df_length = len(df) while current < target_val and row_num < df_length: current += df.iloc[row_num]["Output_Energy"] row_num += 1 if current >= target_val: stop_timestamp = df.index[row_num - 1] print(f"累计至{stop_timestamp}时达到阈值,最终数值为{current:.2f}") else: print("现有2天数据的Output_Energy总和不足,无法让初始值累加到80")
注意点
- 运行前请确保你的DataFrame已经按时间索引升序排序,未排序的话先执行
df = df.sort_index() - 你给出的示例数据中单条Output_Energy数值极小,2天总和远达不到50的差值要求,实际测试可调整阈值验证逻辑正确性
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

