Pandas数据处理:按Server分组,基于diff最小值计算Power均值
问题描述
现有如下Pandas DataFrame:
Server Clock 1 Clock 2 Power diff 0 PhysicalWindows1 3400 3300.0 58.5 100.0 1 PhysicalWindows1 3400 3500.0 63.0 100.0 2 PhysicalWindows1 3400 2900.0 25.0 500.0 3 PhysicalWindows2 3600 3300.0 83.8 300.0 4 PhysicalWindows2 3600 3500.0 65.0 100.0 5 PhysicalWindows2 3600 2900.0 10.0 700.0 6 PhysicalLinux1 2600 NaN NaN NaN 7 PhysicalLinux1 2600 NaN NaN NaN 8 Test 2700 2700.0 30.0 0.0
需求说明
对每个Server分组后执行以下操作:
- 仅保留
diff列值为该分组最小值的行; - 若分组内有多条符合条件的行,对
Power列求均值; - 若仅一条符合条件的行,直接取该行的
Power值; - 若
Power列全为NaN,保留NaN。
期望输出结果:
Server Clock 1 Power 0 PhysicalWindows1 3400 60.75 1 PhysicalWindows2 3600 65.0 2 PhysicalLinux1 2600 NaN 3 Test 2700 30.0
解决方案
通过Pandas的分组、筛选和聚合操作可实现需求,代码如下:
import pandas as pd # 构造原始DataFrame(若已有可跳过此步) data = { 'Server': ['PhysicalWindows1', 'PhysicalWindows1', 'PhysicalWindows1', 'PhysicalWindows2', 'PhysicalWindows2', 'PhysicalWindows2', 'PhysicalLinux1', 'PhysicalLinux1', 'Test'], 'Clock 1': [3400, 3400, 3400, 3600, 3600, 3600, 2600, 2600, 2700], 'Clock 2': [3300.0, 3500.0, 2900.0, 3300.0, 3500.0, 2900.0, None, None, 2700.0], 'Power': [58.5, 63.0, 25.0, 83.8, 65.0, 10.0, None, None, 30.0], 'diff': [100.0, 100.0, 500.0, 300.0, 100.0, 700.0, None, None, 0.0] } df = pd.DataFrame(data) # 1. 计算每个Server分组的diff最小值并广播到原表行 min_diff_per_group = df.groupby('Server')['diff'].transform('min') # 2. 筛选出diff等于分组最小值的行 filtered_rows = df[df['diff'] == min_diff_per_group] # 3. 分组聚合:Clock 1取组内唯一值,Power取均值 result = filtered_rows.groupby('Server').agg( {'Clock 1': 'first', 'Power': 'mean'} ).reset_index() # 输出结果 print(result)
代码说明
- 步骤1:用
transform方法将每个分组的diff最小值同步到原DataFrame的对应行,避免手动匹配分组; - 步骤2:通过布尔索引筛选出符合
diff为分组最小值的行; - 步骤3:对筛选后的子集再次按
Server分组,Clock 1取组内第一个值(因同一Server的Clock 1值一致),Power取均值——自动适配单条/多条符合条件的行,全NaN时均值保持NaN,完全匹配需求。
执行后输出结果:
Server Clock 1 Power 0 PhysicalLinux1 2600 NaN 1 PhysicalWindows1 3400 60.75 2 PhysicalWindows2 3600 65.00 3 Test 2700 30.00
内容的提问来源于stack exchange,提问作者ReactNewbie123
相关产品推荐
相关产品推荐

