计算DataFrame排除指定列组后的行均值(RowMeans)
问题与解决方案
问题描述
现有如下DataFrame:
Leaf1 Leaf2 Leaf3 Root1 Root2 Root3 Shoot1 Shoot2 Shoot3 1 2 3 4 5 6 2 4 5 46 22 33 44 11 33 22 44 33 100 22 2 33 2 222 2222 2113 2827
需要计算每行的均值,但依次排除Leaf、Root、Shoot列组,生成包含Root、Shoot、Leaf三列的新DataFrame——每列对应排除对应列组后的行均值。
解决方案
使用Pandas可以轻松实现需求,核心思路是筛选出目标列组外的所有列,再计算每行均值:
import pandas as pd # 构造原始DataFrame data = { 'Leaf1': [1, 46, 100], 'Leaf2': [2, 22, 22], 'Leaf3': [3, 33, 2], 'Root1': [4, 44, 33], 'Root2': [5, 11, 2], 'Root3': [6, 33, 222], 'Shoot1': [2, 22, 2222], 'Shoot2': [4, 44, 2113], 'Shoot3': [5, 33, 2827] } df = pd.DataFrame(data) # 生成结果DataFrame result = pd.DataFrame() # 排除Leaf列组,计算Root+Shoot的行均值 result['Root'] = df.loc[:, ~df.columns.str.startswith('Leaf')].mean(axis=1) # 排除Root列组,计算Leaf+Shoot的行均值 result['Shoot'] = df.loc[:, ~df.columns.str.startswith('Root')].mean(axis=1) # 排除Shoot列组,计算Leaf+Root的行均值 result['Leaf'] = df.loc[:, ~df.columns.str.startswith('Shoot')].mean(axis=1) # 输出结果 print(result)
代码说明
df.columns.str.startswith('Leaf'):判断列名是否以Leaf开头,返回布尔数组~:取反操作,筛选出不以目标前缀开头的所有列mean(axis=1):按行计算均值
运行结果
Root Shoot Leaf 0 4.333333 2.777778 3.500000 1 31.166667 31.555556 31.500000 2 2349.333333 1361.111111 60.166667
内容的提问来源于stack exchange,提问作者Patrick Thomas
相关产品推荐
相关产品推荐

