如何基于指定小时的所有行计算并向Pandas DataFrame添加新行?
解决方法
可以通过分组计算+合并的方式实现需求,具体步骤如下:
1. 分组计算每个小时的"Other"值
按DateTime字段分组,对每个分组执行以下操作:
- 提取该小时
Total Usage对应的kWh数值 - 计算该小时内除
Total Usage外所有设备的kWh总和 - 用
Total Usage的数值减去上述总和,得到"Other"对应的kWh值
2. 生成"Other"行的DataFrame
基于分组计算结果,构造包含DateTime、固定为"Other"的Name、计算得到的kWh的新DataFrame。
3. 合并数据并重置索引
将原DataFrame与新生成的"Other"行DataFrame合并,最后重置索引即可得到目标结果。
完整代码示例
import pandas as pd # 假设原始数据已加载到df中 other_rows = [] for dt, group in df.groupby('DateTime'): # 获取当前小时的Total Usage数值 total_kwh = group.loc[group['Name'] == 'Total Usage', 'kWh'].iloc[0] # 计算除Total外的设备用电量总和 sum_devices = group.loc[group['Name'] != 'Total Usage', 'kWh'].sum() # 计算Other的用电量 other_kwh = total_kwh - sum_devices # 整理成字典加入列表 other_rows.append({'DateTime': dt, 'Name': 'Other', 'kWh': round(other_kwh, 3)}) # 转换为DataFrame other_df = pd.DataFrame(other_rows) # 合并原数据与Other行 result_df = pd.concat([df, other_df], ignore_index=True) # 按时间排序并重置索引(可选,保证同小时数据集中) result_df = result_df.sort_values('DateTime').reset_index(drop=True) print(result_df)
结果验证
运行代码后会得到符合预期的结果:
- 1/31/2024 18:00的Other值为
1.927 - (0.003+0.027+0.211+0.302+0.811+0.003+0.030+0.069) = 0.471 - 1/31/2024 19:00的Other值为
1.593 - (0.002+0.828+0.001+0.02+0.070) = 0.672
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

